# Returns true if str starts with one of the prefixes given. 'hello'.start_with? 'hell' # => true # Returns true if one of the prefixes matches. 'hello'.start_with? 'heaven', 'hell' # => true 'hello'.start_with? 'heaven', 'paradise' # => false
# Converts pattern to a Regexp (if it isn’t already one), then returns a true or false indicating whether the regexp is matched without updating $~ and other related variables. 'Ruby'.match? %r{P...} # => false 'Ruby'.match? %r{R...} # => true $~ # => nil
regular expression literal with the === operator allows you to compare against a String. # Case Equality — Used in case statements. %r{^[a-z]*$} === 'HELLO' # => false %r{^[A-Z]*$} === 'HELLO' # => true case 'HELLO' when %r{^[a-z]*$} then 'Lower case' when %r{^[A-Z]*$} then 'Upper case' end # =>'Upper case'
be used for capturing. Capture groups can be referred to by name when defined with the (?<name>) or (?'name') constructs. %r{\$(?<dollars>\d+)\.(?<cents>\d+)}.match '$3.67' # => #<MatchData "$3.67" dollars:"3" cents:"67"> $~['dollars'] # => "3" $~['cents'] # => "67"
Hash using named capture. A key of the hash is a name of the named captures. A value of the hash is a string of last successful capture of corresponding group. %r{\$(?<dollars>\d+)\.(?<cents>\d+)}.match '$3.67' # => #<MatchData "$3.67" dollars:"3" cents:"67"> $~.named_captures # => {"dollars" => "3", "cents"=> "67"}
Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or nil otherwise. (1..90).find {|i| i % 5 == 0 and i % 7 == 0} # => 35 (1..10).find {|i| i % 5 == 0 and i % 7 == 0} # => nil (1..10).find(-> {0}) do |i| i % 5 == 0 and i % 7 == 0 end # => 0
to leave a block early. break accepts a value that supplies the result of the expression it is "breaking" out of: (1..10).each{|value| break if value.even?} # => nil (1..10).each do |value| break(value * 2) if value.even? end # => 4
%r{youtube\.com/(?<name>[\w-]+)} => :channel, } PATTERNS.find do |regex, type| if text.match(regex) …return the Regexp captures and the matched type… end end
%r{youtube\.com/(?<name>[\w-]+)} => :channel, } PATTERNS.find(-> { {type: :unknown} }) do |regex, type| if text.match(regex) break $~.named_captures.merge(type: type) end end
used as an Enumerable. Iteration is defined by the given block, in which a "yielder" object, given as block parameter, can be used to yield a value by calling the yield method (aliased as <<): fib = Enumerator.new do |y| a = b = 1 loop{ y << a; a, b = b, a + b } end fib.take(10) # => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]