Professional Documents
Culture Documents
musicians.size # => 4
musicians[1] # => "Roger Waters"
musicians << 'Syd Barrett' # => [..., 'Syd Barrett']
RANGE
Collection of successive elements
0..10 # including upper bound
# => 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
p upcased_musicians
# => ['DAVID GILMOUR', 'ROGER WATERS', 'RICHARD WRIGHT', 'NICK MASON']
#MAP - FIRST NAMES
Live-code: Let's build an array of musician first names.
musicians = ['David Gilmour', 'Roger Waters', 'Richard Wright'
p musician_first_names
# => ['David', 'Roger', 'Richard', 'Nick']
#COUNT
Count element of an array for which some code is true
Live-code: count musicians starting with "R"
musicians = ['David Gilmour', 'Roger Waters', 'Richard Wright'
p r_musicians_count
# => 2
#SELECT
Filter from an array elements for which some code is true
Live-code: extract musicians starting with "R"
musicians = ['David Gilmour', 'Roger Waters', 'Richard Wright'
p r_musicians
# => ['Roger Waters', 'Richard Wright']
AND MANY MORE
http://www.ruby-doc.org/core/Array.html
http://www.ruby-doc.org/core/Enumerable.html
multi-line syntax
do |num|
num * 2
end
BLOCK RETURN
A multi-line block works as a method, it returns the last
statement executed.
musicians = ['David Gilmour', 'Roger Waters', 'Richard Wright'
upcased_first_name
end
METHODS USING A BLOCK
Multi-line syntax
method(arg_1, ...) do |block_arg_1, ...| # A block can pass on multipl
# Some code
end
IMPORTANT
The block is just an argument of the method
EXAMPLE #EACH
[1, 2, 3].each do |number|
# Do what ever you want with each number
end
timer() do
puts "I'm doing something slow..."
sleep(4)
puts "I'm done :)"
end
# => I'm doing somethings slow...
# => I'm done :)
# => Elapsed time: 4s
FLOW OF A METHOD CALLED WITH A BLOCK (1)
FLOW OF A METHOD CALLED WITH A BLOCK (2)
FLOW OF A METHOD CALLED WITH A BLOCK (3)
FLOW OF A METHOD CALLED WITH A BLOCK (4)
FLOW OF A METHOD CALLED WITH A BLOCK (5)
YIELD CAN BE CALLED WITH PARAMETERS
Live-code: let's code a custom greeting method.
def greet(first_name, last_name)
full_name = "#{first_name.capitalize} #{last_name.upcase}"
return "Hello, #{full_name}"
end