How can one set property values when initializing an object in Ruby?

前端 未结 8 2142
清歌不尽
清歌不尽 2021-01-01 16:09

Given the following class:

class Test
  attr_accessor :name
end

When I create the object, I want to do the following:

t = Test         


        
8条回答
  •  醉酒成梦
    2021-01-01 16:33

    As mentioned by others, the easiest way to do this would be to define an initialize method. If you don't want to do that, you could make your class inherit from Struct.

    class Test < Struct.new(:name)
    end
    

    So now:

    >> t = Test.new("Some Test Object")
    => #
    >> t.name
    => "Some Test Object"
    

提交回复
热议问题