Ruby Language Common quick usage


Example

Regular expressions are often used in methods as parameters to check if other strings are present or to search and/or replace strings.

You'll often see the following:

string = "My not so long string"
string[/so/] # gives so
string[/present/] # gives nil
string[/present/].nil? # gives true

So you can simply use this as a check if a string contains a substring

puts "found" if string[/so/]

More advanced but still short and quick: search for a specific group by using the second parameter, 2 is the second in this example because numbering starts at 1 and not 0, a group is what is enclosed in parentheses.

string[/(n.t).+(l.ng)/, 2] # gives long

Also often used: search and replace with sub or gsub, \1 gives the first found group, \2 the second:

string.gsub(/(n.t).+(l.ng)/, '\1 very \2') # My not very long string

The last result is remembered and can be used on the following lines

$2 # gives long