From 7f83bd832280c28acc7b24d8e8e089bc6c889e58 Mon Sep 17 00:00:00 2001 From: franzejr Date: Fri, 18 Dec 2015 09:58:27 -0300 Subject: [PATCH] Add Introspecting Block Parameters --- SUMMARY.md | 1 + idiomatic_ruby.md | 2 +- .../introspecting_block_parameters.md | 51 +++++++++++++++++++ 3 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 idiomatic_ruby/introspecting_block_parameters.md diff --git a/SUMMARY.md b/SUMMARY.md index 1fc7926..d5606a2 100644 --- a/SUMMARY.md +++ b/SUMMARY.md @@ -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) diff --git a/idiomatic_ruby.md b/idiomatic_ruby.md index 004b7b3..7d3ead9 100644 --- a/idiomatic_ruby.md +++ b/idiomatic_ruby.md @@ -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) diff --git a/idiomatic_ruby/introspecting_block_parameters.md b/idiomatic_ruby/introspecting_block_parameters.md new file mode 100644 index 0000000..3aeac48 --- /dev/null +++ b/idiomatic_ruby/introspecting_block_parameters.md @@ -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