String tools

Split and join

The method split cuts a string into an array around a separator. Without arguments it splits on whitespace, which tidies messy input. The method join performs the reverse trip, gluing an array back together with a separator between elements.

words = "Ada,Bob,Lin".split(",") puts words.length puts words.join(" and ")

3
Ada and Bob and Lin

sub/gsub and replace

The method sub replaces the first match, while gsub replaces every match in the whole string. Both build a fresh string and leave the original untouched. Bang variants ending with an exclamation mark rewrite the string in place instead.

s = "aaa" puts s.sub("a", "o") puts s.gsub("a", "o") puts s

oaa
ooo
aaa

Regexp match

The operator =~ returns the index of the first match, or nil when nothing matches. The method match returns a MatchData object, with captures available in brackets. The predicate match? gives a plain boolean when the captures are not needed.

s = "age 36" puts(s =~ /[0-9]+/) m = s.match(/([0-9]+)/) puts m[1] puts s.match?(/[0-9]+/)

4
36
true

The digits start at index 4, and the first capture group holds 36.

sprintf

The methods format and sprintf fill a template with values: %d takes an integer, %s takes a string, and %.2f rounds a float to two decimals. Templates keep padding and precision in one readable place.

puts format("%d plus %d is %d", 2, 3, 5) puts sprintf("%.2f", 3.14159)

2 plus 3 is 5
3.14

Next: puts, print and p

Article author: Arthur Isaev