Skip to content

Instantly share code, notes, and snippets.

@toandv
Created September 13, 2015 17:19
Show Gist options
  • Save toandv/f41e6a2a83c0eee1367e to your computer and use it in GitHub Desktop.
Save toandv/f41e6a2a83c0eee1367e to your computer and use it in GitHub Desktop.
instance_variables_from_hash
book_params = {price: 100, isbn: 100}
puts book_params.class.name
puts p.inspect
class Book
def initialize(book_params)
if (book_params.instance_of? Hash)
book_params.each do |k, v|
instance_variable_set("@#{k}", v)
# set accessors
genclass = class<<self; self; end
genclass.class_eval do
attr_reader k
attr_accessor k
end
end
end
end
end
b = Book.new(book_params)
puts b.inspect
puts b.price
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment