Skip to content

Commit

Permalink
Merge pull request #49 from franzejr/introspecting-block-parameters
Browse files Browse the repository at this point in the history
Add Introspecting Block Parameters
  • Loading branch information
filipebarcos committed Dec 23, 2015
2 parents 72fa79c + 9e53c0b commit 879b81a
Show file tree
Hide file tree
Showing 4 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 @@ -44,6 +44,7 @@
* [Unused variable format](tricks/unused-variable-format.md)
* [Variables from a regex](tricks/variables-from-a-regex.md)
* [Zip](tricks/zip.md)
* [Introspecting Block Parameters](tricks/introspecting_block_parameters.md)
* [Idiomatic Ruby](idiomatic_ruby.md)
* [Each vs map](idiomatic_ruby/each_vs_map.md)
* [Conditional assignment](idiomatic_ruby/conditional_assignment.md)
Expand Down
1 change: 0 additions & 1 deletion idiomatic_ruby.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,3 @@
* [Array Sample (enumerables)](idiomatic_ruby/array_sample.md)
* [Use Fixnum#times](idiomatic_ruby/use_times.md)
* [Implicit Return](idiomatic_ruby/implicit_return.md)

1 change: 1 addition & 0 deletions tricks.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,4 @@ The majority of these Ruby Tricks were extracted from James Edward Gray II [talk
* [Unused variable format](tricks/unused-variable-format.md)
* [Variables from a regex](tricks/variables-from-a-regex.md)
* [Zip](tricks/zip.md)
* [Introspecting Block Parameters](tricks/introspecting_block_parameters.md)
51 changes: 51 additions & 0 deletions tricks/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 879b81a

Please sign in to comment.