A Struct is a convenient way to bundle a number of attributes together, using accessor methods, without having to write an explicit class.

The Struct class is a generator of specific classes, each one of which is defined to hold a set of variables and their accessors. In these examples, we'll call the generated class ``CustomerClass,'' and we'll show an example instance of that class as ``CustomerInst.''

In the descriptions that follow, the parameter symbol refers to a symbol, which is either a quoted string or a Symbol (such as :name).

Show files where this class is defined (3 files)
Register or log in to add new notes.
July 1, 2009
4 thanks


User = Struct.new(:name, :phone)

marc = User.new(“Marc”, “555-5555”)

February 12, 2012 - (v1_8_6_287 - v1_9_2_180)
2 thanks

More Examples


class User < Struct.new(:name, :age, :gender) 

user = User.new("Matz", 43, "male")
January 28, 2011 - (>= v1_8_7_72)
1 thank

Passing a block with methods

Code example

Google = Struct.new(:address) do
  def latitude

  def longitude

  def with_address
    "with #{address}"

g = Google.new("Some Addres")

puts g.address
puts g.latitude
puts g.longitude
puts g.with_address


# >> Some Addres
# >> -1
# >> -2
# >> with Some Addres