diff options
author | Adam Bard <github@adambard.com> | 2013-08-13 07:44:27 -0700 |
---|---|---|
committer | Adam Bard <github@adambard.com> | 2013-08-13 07:44:27 -0700 |
commit | d088d4f1559d50e4c923bd5968704c6ebe1d34ff (patch) | |
tree | a0d2ea31d67372483e66a331ea50d6c78ca37bf8 | |
parent | 46eace2b7801f0ed85c6ef7c7cea39f398df8858 (diff) | |
parent | 5c5c8d3c4a0aea7c1c7a8150f428e354d0a12a6c (diff) |
Merge pull request #198 from trishume/master
Explain Blocks In Ruby
-rw-r--r-- | ruby.html.markdown | 28 |
1 files changed, 20 insertions, 8 deletions
diff --git a/ruby.html.markdown b/ruby.html.markdown index 861a94ad..68c5b524 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -5,6 +5,7 @@ contributors: - ["David Underwood", "http://theflyingdeveloper.com"] - ["Joel Walden", "http://joelwalden.net"] - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] --- ```ruby @@ -158,11 +159,6 @@ hash['number'] #=> 5 # Asking a hash for a key that doesn't exist returns nil: hash['nothing here'] #=> nil -# Iterate over hashes with the #each method: -hash.each do |k, v| - puts "#{k} is #{v}" -end - # Since Ruby 1.9, there's a special syntax when using symbols as keys: new_hash = { defcon: 3, action: true} @@ -191,9 +187,14 @@ end #=> iteration 4 #=> iteration 5 -# HOWEVER -# No-one uses for loops -# Use `each` instead, like this: +# HOWEVER, No-one uses for loops. +# Instead you should use the "each" method and pass it a block. +# A block is a bunch of code that you can pass to a method like "each". +# It is analogous to lambdas, anonymous functions or closures in other programming languages. +# +# The "each" method of a range runs the block once for each element of the range. +# The block is passed a counter as a parameter. +# Calling the "each" method with a block looks like this: (1..5).each do |counter| puts "iteration #{counter}" @@ -204,6 +205,17 @@ end #=> iteration 4 #=> iteration 5 +# You can also surround blocks in curly brackets: +(1..5).each {|counter| puts "iteration #{counter}"} + +# The contents of data structures can also be iterated using each. +array.each do |element| + puts "#{element} is part of the array" +end +hash.each do |key, value| + puts "#{key} is #{value}" +end + counter = 1 while counter <= 5 do puts "iteration #{counter}" |