mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2025-04-27 07:33:57 +00:00
Explain blocks better
This commit is contained in:
parent
bd48b7062c
commit
5424b31848
@ -5,6 +5,7 @@ contributors:
|
|||||||
- ["David Underwood", "http://theflyingdeveloper.com"]
|
- ["David Underwood", "http://theflyingdeveloper.com"]
|
||||||
- ["Joel Walden", "http://joelwalden.net"]
|
- ["Joel Walden", "http://joelwalden.net"]
|
||||||
- ["Luke Holder", "http://twitter.com/lukeholder"]
|
- ["Luke Holder", "http://twitter.com/lukeholder"]
|
||||||
|
- ["Tristan Hume", "http://thume.ca/"]
|
||||||
---
|
---
|
||||||
|
|
||||||
```ruby
|
```ruby
|
||||||
@ -158,11 +159,6 @@ hash['number'] #=> 5
|
|||||||
# Asking a hash for a key that doesn't exist returns nil:
|
# Asking a hash for a key that doesn't exist returns nil:
|
||||||
hash['nothing here'] #=> 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:
|
# Since Ruby 1.9, there's a special syntax when using symbols as keys:
|
||||||
|
|
||||||
new_hash = { defcon: 3, action: true}
|
new_hash = { defcon: 3, action: true}
|
||||||
@ -193,7 +189,12 @@ end
|
|||||||
|
|
||||||
# HOWEVER
|
# HOWEVER
|
||||||
# No-one uses for loops
|
# No-one uses for loops
|
||||||
# Use `each` instead, like this:
|
# Under the hood for loops use the each method which takes 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 runs the block multiple times passing a counter.
|
||||||
|
# You can iterate over a range like this:
|
||||||
|
|
||||||
(1..5).each do |counter|
|
(1..5).each do |counter|
|
||||||
puts "iteration #{counter}"
|
puts "iteration #{counter}"
|
||||||
@ -204,6 +205,17 @@ end
|
|||||||
#=> iteration 4
|
#=> iteration 4
|
||||||
#=> iteration 5
|
#=> iteration 5
|
||||||
|
|
||||||
|
# You can also surround blocks in curly brackets:
|
||||||
|
(1..5).each {|counter| puts "iteration #{counter}"}
|
||||||
|
|
||||||
|
# You can also iterate over the contents of data structures 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
|
counter = 1
|
||||||
while counter <= 5 do
|
while counter <= 5 do
|
||||||
puts "iteration #{counter}"
|
puts "iteration #{counter}"
|
||||||
|
Loading…
Reference in New Issue
Block a user