Ruby strings are powerful. You could say Ruby is built around manipulating strings. There are tons of ways how to work with strings and as of Ruby 2.7.1 String
offers 130 instance methods. Knowing them well can save you a lot of time.
What follows is a list of 10 lesser known things about strings: Some of them useful, some of them idiosyncratic, some both.
Named Format Strings
Btw, Ruby's format strings can be used with hashes:
"%<language>s: %<author>s" % { language: "Ruby", author: "matz" } #=> "Ruby: matz"
— Ruby String Magic (@RubyStrings) October 28, 2014
String Concatenation
There is a lesser-known syntax for concatenating string literals: "just" "put" "them" "directly""after" "each" "other"
— Ruby String Magic (@RubyStrings) September 11, 2014
Strings + Empty Ranges
Ruby is strange. How can an *empty* range have an effect when applied to a string?
r = 0..-3
r.to_a.empty? #=> true
"Ruby"[r] #=> "Ru"
— Ruby String Magic (@RubyStrings) October 6, 2014
Whitespace Matching
Unicode is full of whitespaces. This is how you match them:
a=" " #=> " "
a.scan(/\s/).size #=> 1
a.scan(/[[:space:]]/).size #=> 5
— Ruby String Magic (@RubyStrings) December 1, 2014
String#succ
Ruby's weird calculation of string successors:
"9z".succ #=> "10a"
"z9".succ #=> "aa0"
— Ruby String Magic (@RubyStrings) October 9, 2014
Stdlib String Compression
Simple stdlib string compression:
require 'zlib'
s = "Ruby"*99
s.size #=> 396
c = Zlib.deflate(s)
c.size #=> 17
Zlib.inflate(c) == s #=>true
— Ruby String Magic (@RubyStrings) September 16, 2014
Using Regex Groups in String#[]
You can use regex incl. captured groups when accessing substrings via the [] method: "#42"[/.(\d+)/, 1] #=> "42"
— Ruby String Magic (@RubyStrings) September 7, 2014
Rexep.union
If you have an array of strings, you can automatically generate a regex that matches any the strings: regex = Regexp.union(array_of_strings)
— Ruby String Magic (@RubyStrings) September 12, 2014
Convert a String from snake_case to CamelCase
You can camelize a string (some_string => SomeString) with:
"some_string".gsub(/(?:^|_)([a-z])/) do $1.upcase end
— Ruby String Magic (@RubyStrings) September 9, 2014
Convert a String from CamelCase to snake_case
You can snakify a string (SomeString => some_string) with:
"SomeString".gsub(/(?<!^)[A-Z]/) do "_#$&" end.downcase
— Ruby String Magic (@RubyStrings) September 8, 2014
Resources
More Idiosyncratic Ruby
- Please Comment on GitHub
- Next Article: Ruby, Can You Speak Louder?
- Previous Article: Test Highlights