-
Notifications
You must be signed in to change notification settings - Fork 218
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #49 from franzejr/introspecting-block-parameters
Add Introspecting Block Parameters
- Loading branch information
Showing
4 changed files
with
53 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
## Introspecting Block Parameters | ||
|
||
Suppose you would like to iterate over a hash, get its elements and use those | ||
in a block. One thing you can do is use `Proc#parameters` to help you. | ||
|
||
For example: | ||
|
||
```ruby | ||
hash = { | ||
first_name: "John", | ||
last_name: "Smith", | ||
age: 35, | ||
# ... | ||
} | ||
|
||
hash.using do |first_name, last_name| | ||
puts "Hello, #{first_name} #{last_name}." | ||
end | ||
|
||
# or even... | ||
|
||
circle = { | ||
radius: 5, | ||
color: "blue", | ||
# ... | ||
} | ||
|
||
area = circle.using { |radius| Math::PI * radius**2 } | ||
``` | ||
|
||
You can check how the implementation is really simple: | ||
|
||
```ruby | ||
class Hash | ||
module Using | ||
def using(&block) | ||
values = block.parameters.map do |(type, name)| | ||
self[name] | ||
end | ||
|
||
block.call(*values) | ||
end | ||
end | ||
|
||
include Using | ||
end | ||
``` | ||
|
||
From: | ||
|
||
http://weblog.jamisbuck.org/2015/12/12/little-things-proc-parameters.html |