new(*args) public

The first two forms are used to create a new Struct subclass class_name that can contain a value for each member_name. This subclass can be used to create instances of the structure like any other Class.

If the class_name is omitted an anonymous structure class will be created. Otherwise, the name of this struct will appear as a constant in class Struct, so it must be unique for all Structs in the system and must start with a capital letter. Assigning a structure class to a constant also gives the class the name of the constant.

# Create a structure with a name under Struct
Struct.new("Customer", :name, :address)
#=> Struct::Customer
Struct::Customer.new("Dave", "123 Main")
#=> #<struct Struct::Customer name="Dave", address="123 Main">

If a block is given it will be evaluated in the context of StructClass, passing the created class as a parameter:

Customer = Struct.new(:name, :address) do
  def greeting
    "Hello #{name}!"
  end
end
Customer.new("Dave", "123 Main").greeting  # => "Hello Dave!"

This is the recommended way to customize a struct. Subclassing an anonymous struct creates an extra anonymous class that will never be used.

The last two forms create a new instance of a struct subclass. The number of value parameters must be less than or equal to the number of attributes defined for the structure. Unset parameters default to nil. Passing more parameters than number of attributes will raise an ArgumentError.

# Create a structure named by its constant
Customer = Struct.new(:name, :address)
#=> Customer
Customer.new("Dave", "123 Main")
#=> #<struct Customer name="Dave", address="123 Main">
Show source
Register or log in to add new notes.
July 31, 2015
0 thanks

Also takes a block

You can define methods within a block

User = Struct.new(:first_name, :last_name) do
  def full_name
    "#{first_name} #{last_name}"
  end
end

user = User.new('Simon', 'Templar') # => #<struct User first_name="Simon", last_name="Templar">
user.full_name # => "Simon Templar"