Skip to content

Instantly share code, notes, and snippets.

@steveklabnik
Created February 14, 2012 17:56
Show Gist options
  • Save steveklabnik/1828595 to your computer and use it in GitHub Desktop.
Save steveklabnik/1828595 to your computer and use it in GitHub Desktop.
Metaprogramming rots your brain.
# Metaprogramming rots your brain.
# First I wrote this:
Data = Struct.new(:title)
data.collect{|datum| Data.new(datum["title"])}
# Then I decided I didn't want to make a huge list of attributes, so I decided to use an
# OpenStruct, and ended up doing this:
data.collect do |datum|
OpenStruct.new.tap do |struct|
datum.each do |key, value|
struct.send("#{key}=", value)
end
end
end
# I was like "that's not too bad, but there must be a simpler way."
#
# Of course there is. Duh:
data.collect {|d| OpenStruct.new(d) }
# Metaprogramming rots your brain.
@supaspoida
Copy link

data.collect &OpenStuct.method(:new)

:D

@steveklabnik
Copy link
Author

Ha! There's a proposal for a Const#to_proc that I don't think ruby-core will go for. It'd make it just

data.collect &OpenStruct

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