user2950593 user2950593 - 7 months ago 8
Ruby Question

How to add property to ruby variable?

I want to create variable

item

And write something like this:

item.property1 = "whatever"
item.poperty2 = "whatever"


How do I do this?

Right now I am doing it like this:
item = {}
item [:property1] = "whatever"


Any other options?

Answer

Here are the simplest solutions I know of:

If you know the attributes in advance, then use a Struct:

Item = Struct.new(:property1, :property2)
item = Item.new('blue', 'medium')  # or:
item = Item.new
item.property1 = 'blue'
item.property2 = 'medium'

puts item.property1
puts item.property2

Otherwise, you can use an OpenStruct:

require 'ostruct'
item = OpenStruct.new('blue', 'medium')  # or:
item = OpenStruct.new
item.property1 = 'blue'
item.property2 = 'medium'

puts item.property1
puts item.property2