Created
March 14, 2016 13:11
-
-
Save remigijusj/93f15632361fab1a43df to your computer and use it in GitHub Desktop.
Hash#using
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
class Hash | |
def using(&block) | |
values = block.parameters.map do |(type, name)| | |
self[name] | |
end | |
block.call(*values) | |
end | |
end | |
hash = { | |
first_name: "John", | |
last_name: "Smith", | |
age: 35, | |
# ... | |
} | |
hash.using do |first_name, last_name| | |
puts "Hello, #{first_name} #{last_name}." | |
end | |
circle = { | |
radius: 5, | |
color: "blue", | |
# ... | |
} | |
area = circle.using { |radius| Math::PI * radius**2 } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
when key is a String, then this
self[name]
won't work. With rails helpers: