Ruby monstas Ruby cheat sheet, Part 3
Blocks
Name
Description
Structure
Examples
5 . t i m e s d o | i |
times
Iterates the given block int times, passing in values from
number.times do |i|
p u t s i
zero to int 1.
code
e n d
end
or
5 . t i m e s d o
numbers.times do
p u t s “ H e l l o w o r l d ! ”
code
e n d
end
n u m b e r s . c o l l e c t d o | n u m b e r |
collect
Creates a new array containing the values returned by the
array.collection do |value|
n u m b e r + 1
block.
code
e n d
end
n u m b e r s . s e l e c t d o | n u m b e r |
select
Returns a new array containing all elements of the array
array.select do |value|
n u m b e r . o d d ?
for which the given block returns a true value.
return boolean expression
e n d
end
n u m b e r s . d e t e c t d o | n u m b e r |
detect
Passes each entry in enum to block. Returns the first for
array.detect do |value|
n u m b e r . e v e n ?
which block is not false. If no object matches then it
return boolean expression
e n d
returns nil.
end