Struct.new( [aString] [, aSym]+> ) {|StructClass| block } â StructClass
StructClass.new(arg, ...) â obj
StructClass[arg, ...] â obj
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 Struct
s 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.
If a block is given, it will be evaluated in the context of StructClass, passing StructClass as a parameter.
Customer = Struct.new(:name, :address) do def greeting "Hello #{name}!" end end Customer.new("Dave", "123 Main").greeting # => "Hello Dave!"
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">
Please login to continue.