A
A
Alexander2016-02-03 00:07:35
ruby
Alexander, 2016-02-03 00:07:35

How to beautifully write assignment of an array value to an object in Ruby?

I'm just a beginner rubist

obj.fio = data_after["fio"]
obj.phone = data_after["phone"]
obj.email = data_after["email"]
obj.address= data_after["address"]
obj.skype = data_after["skype"]
...

I don’t know how, but I think in ruby ​​there is definitely a way to more elegantly write the assignment of an array value to an object, when the array key is the name of the object’s property

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeniy Trebin, 2016-02-03
@evgeniy_trebin

class MyClass
  attr_accessor :name, :surname, :email
end

obj = MyClass.new

hash = {name: 'Ivan', surname: 'Ivanov', email: '[email protected]'}

hash.each do |key, value|
  obj.public_send(%Q{#{key}=}, value) if obj.respond_to?(%Q{#{key}=})
end
p obj # => #<MyClass:0x007f9a4c11c478 @name="Ivan", @surname="Ivanov", @email="[email protected]">

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question