class Foo attr_accessor :name, :age, :email, :gender, :height def initalize params @name = params[:name] @age = params[:age] @email = params[:email] . . . end
This seems like a silly way of doing it. What is a better/more idiomatic way of initalizing objects in Ruby?
Ruby 1.9.3
new , the class will create a new instance of itself. It will then, internally, call the method initialize on the new object. Doing so it will simply pass all the arguments that you passed to new on to the method initialize .
The attr method creates an instance variable and a getter method for each attribute name passed as argument. An argument can be a Symbol or a String that will be converted to Symbol module Attr.
The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object. Below are some points about Initialize : We can define default argument. It will always return a new object so return keyword is not used inside initialize method.
You can just iterate over the keys and invoke the setters. I prefer this, because it will catch if you pass an invalid key.
class Foo attr_accessor :name, :age, :email, :gender, :height def initialize params = {} params.each { |key, value| send "#{key}=", value } end end foo = Foo.new name: 'Josh', age: 456 foo.name # => "Josh" foo.age # => 456 foo.email # => nil
def initialize(params) params.each do |key, value| instance_variable_set("@#{key}", value) end end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With