Skip to content

Instantly share code, notes, and snippets.

@xwmx
Created August 5, 2009 21:02
Show Gist options
  • Save xwmx/162953 to your computer and use it in GitHub Desktop.
Save xwmx/162953 to your computer and use it in GitHub Desktop.
# Referring to http://blog.rubybestpractices.com/posts/gregory/011-tap-that-hash.html
# Ruby 1.9, no tap, single line
Hash[[:x, :y, :z].map { |l| [l, rand(100)]}]
# Ruby 1.9/1.8, no tap, inject, single line
[:x, :y, :z].inject({}) { |result, l| result[l] = rand(100); result}
# Ruby 1.9/1.8, no tap, each_with_object from ActiveSupport, single line
[:x, :y, :z].each_with_object({}) { |l, result| result[l] = rand(100) }
# Ruby 1.8, no tap, single line
Hash[*[[:x, :y, :z].map { |l| [l, rand(100)]}].flatten]
# Ruby 1.9/1.8, no tap, initialed variable, multiline
result = {}
[:x, :y, :z].map { |l| result[l] = rand(100)}
result
# Ruby 1.9 no tap, expanded Hash[], multiline
Hash[
[:x, :y, :z].map { |l| [l, rand(100)]}
]
# Ruby 1.9 tap single line
{}.tap { |result| [:x, :y, :z].map { |l| result[l] = rand(100)} }
# Ruby 1.9 tap multiline
{}.tap do |result|
[:x, :y, :z].map do |l|
result[l] = rand(100)
end
end
# Ruby 1.9/1.8, returning from ActiveSupport, multiline
returning({}) do |result|
[:x, :y, :z].each do |l|
result[l] = rand(100)
end
end
# Python 3
{(x, random.randrange(100)) for x in ["x", "y", "z"]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment