Look at this piece of code:
class Person
attr_accessor :name, :age
def initialize(data)
data.each { |k, v| self.send("#{k}=", v) }
end
end
data = {
name: 'Luke Skywalker',
age: 19
}
person = Person.new(data)
person.inspect # => #<Person @name="Luke Skywalker", @age=19>
This works fine. It does what it's supposed to do. The thing is, I don't want the attributes to be mutable, in other words, I want to use attr_reader
. I know that if I use attr_reader
Ruby won't create the writer methods for me (def attr=(val) ...
) and therefore I won't be able to use "#{k}="
in send
. I really DON'T want to do this:
class Person
attr_reader :name, :age
def initialize(name:, age:)
@name = name
@age = age
end
end
Do you guys know any workaround to achieve what I want?
Thanks for all the help!