new
new(p1, *args)
public
Creates a new class, named by aString, containing accessor methods for the given symbols. If the name aString 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 should start with a capital letter. Assigning a structure class to a constant effectively gives the class the name of the constant.
Struct::new returns a new Class object, which can then be used to create specific instances of the new structure. The number of actual parameters must be less than or equal to the number of attributes defined for this class; unset parameters default to nil. Passing too many parameters will raise an ArgumentError.
The remaining methods listed in this section (class and instance) are defined for this generated class.
# Create a structure with a name in Struct Struct.new("Customer", :name, :address) #=> Struct::Customer Struct::Customer.new("Dave", "123 Main") #=> #<struct Struct::Customer name="Dave", address="123 Main"> # 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">
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"