Skip to content

Instantly share code, notes, and snippets.

@remigijusj
Created March 14, 2016 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save remigijusj/93f15632361fab1a43df to your computer and use it in GitHub Desktop.
Save remigijusj/93f15632361fab1a43df to your computer and use it in GitHub Desktop.
Hash#using
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 }
@evaldasg
Copy link

when key is a String, then this self[name] won't work. With rails helpers:

hash = self.with_indifferent_access
hash[name]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment