Skip to content

Commit

Permalink
Add Introspecting Block Parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
franzejr committed Dec 18, 2015
1 parent 0f679bb commit 7f83bd8
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
1 change: 1 addition & 0 deletions SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
* [Array Sample (enumerables)](idiomatic_ruby/array_sample.md)
* [Use Fixnum#times](idiomatic_ruby/use_times.md)
* [Implicit Return](idiomatic_ruby/implicit_return.md)
* [Introspecting Block Parameters](idiomatic_ruby/introspecting_block_parameters.md)
* [Refactorings](refactorings.md)
* [Conditionals when object is nil](refactorings/conditionals_when_object_is_nil.md)
* [Switch case with Hashes](refactorings/case_with_hashes.md)
Expand Down
2 changes: 1 addition & 1 deletion idiomatic_ruby.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@
* [Array Sample (enumerables)](idiomatic_ruby/array_sample.md)
* [Use Fixnum#times](idiomatic_ruby/use_times.md)
* [Implicit Return](idiomatic_ruby/implicit_return.md)

* [Introspecting Block Parameters](idiomatic_ruby/introspecting_block_parameters.md)
51 changes: 51 additions & 0 deletions idiomatic_ruby/introspecting_block_parameters.md
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

0 comments on commit 7f83bd8

Please sign in to comment.