Created
September 13, 2015 17:19
-
-
Save toandv/f41e6a2a83c0eee1367e to your computer and use it in GitHub Desktop.
instance_variables_from_hash
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
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