diff --git a/SUMMARY.md b/SUMMARY.md index 1fc7926..315d8cb 100644 --- a/SUMMARY.md +++ b/SUMMARY.md @@ -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) diff --git a/idiomatic_ruby.md b/idiomatic_ruby.md index 004b7b3..a69e2e2 100644 --- a/idiomatic_ruby.md +++ b/idiomatic_ruby.md @@ -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) - diff --git a/tricks.md b/tricks.md index b3613d3..036e7df 100644 --- a/tricks.md +++ b/tricks.md @@ -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) diff --git a/tricks/introspecting_block_parameters.md b/tricks/introspecting_block_parameters.md new file mode 100644 index 0000000..3aeac48 --- /dev/null +++ b/tricks/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