o9s
is a microblog
home archives search feed blogroll


Struct On The Fly

You can create structs on the fly when you need them in Ruby.

Struct.new('NamePhone', :name, :phone)
name_phone = Struct::NamePhone.new('Ruby', '555-555-55555')
p name_phone # <struct Struct::NamePhone name="Ruby", phone="555-555-55555">

You can also use them this way, but Rubocop will complain that a variable should not start with a capital letter.

NamePhone = Struct.new(:name, :phone)
name_phone = NamePhone.new('Ruby', '555-555-55555')
p name_phone # <struct NamePhone name="Ruby", phone="555-555-55555">
Posted on 2018-04-04   #ruby     #til  






← Next post    ยท    Previous post →