ruby - Could any one walk me through this code? -
i'm getting confused iterations - walk me through code does? friends , family hashes , language ruby.
friends.each { |x| puts "#{x}" } family.each { |x, y| puts "#{x}: #{y}" }
friends.each { |x| puts "#{x}" } family.each { |x, y| puts "#{x}: #{y}" }
the first equivalent to:
x = [friends.keys[0], friends.values[0]] puts "#{x}" x = [friends.keys[1], friends.values[1]] puts "#{x}" x = [friends.keys[2], friends.values[2]] puts "#{x}" # ... x = [friends.keys[n], friends.values[n]] puts "#{x}"
the second:
x = family.keys[0] y = family.values[0] puts "#{x}: #{y}" x = family.keys[1] y = family.values[1] puts "#{x}: #{y}" x = family.keys[2] y = family.values[2] puts "#{x}: #{y}" # ... x = family.keys[n] y = family.values[n] puts "#{x}: #{y}"
any time have { |...| ... }
or do |...|; ...; end
after method, creating called block. block passed method, can yield
parameters block. array#each
call block each element; hash#each
pass [key, value]
.
you could, of course, totally different, so:
def test yield('oh my') yield('i really') yield('like blocks') end test { |a| puts }
which outputs
oh blocks
if yield
array block, can assigned multiple or single parameter.
def test yield(['oh', 'my']) yield(['i', 'really']) yield(['like', 'blocks']) end test { |a, b| puts "#{a}-#{b}" }
which outputs
oh-my i-really like-blocks
or, if accept single parameter in block, passed array
test { |a| puts a.inspect }
outputs
["oh", "my"] ["i", "really"] ["like", "blocks"]
so, array#each
doesn't exist , want create yourself. like
class array def each = 0 while < length_of_underlying_array next_element = get_element(i) yield(next_element) end end end
or, hash#each
class hash def each = 0 while < length_of_underlying_hash next_key = keys[i] next_value = values[i] yield([next_key, next_value]) end end end
another general tip, since ruby open source, can see how array#each , hash#each implemented in c, matches plain ruby code above.
Comments
Post a Comment