A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://en.wikibooks.org/wiki/Ruby_Programming/Reference/Objects/Struct below:

Ruby Programming/Reference/Objects/Struct - Wikibooks, open books for an open world

From Wikibooks, open books for an open world

A structure (Struct) is a:

Inside a 'structure' there is a list of fields - example:

Structures are similar to arrays in that they contain multiple data. However, instead of an Index to each piece of data, we have a variable "name". Using the above example:

Struct can be used without any additional require statement.

In Ruby Struct.new takes a set of field names as arguments and returns a new Class.

Newtype = Struct.new(:data1, :data2)
n = Newtype.new  # => <struct Newtype data1=nil, data2=nil>

Class Struct has a method new like other classes. But that method does not return an instance of Struct but rather a class which is a subclass of class Struct. Example:

pnt = Struct.new(:x, :y)    # => #<Class:0x143ce50>
pnt.ancestors #=> [#<Class:0x143d6f0>, Struct, Enumerable, Object, Kernel, BasicObject]

Arguments to Struct.new are names of fields that the generated class will have. These names must be provided as Symbols.

  1. approach / method 1
Struct.new("Point", :x, :y) #=> Struct::Point
origin = Struct::Point.new(0,0)  # #<struct Struct::Point x=0, y=0>
  1. approach / method 2
Structure_example = Struct.new(:filed1, :field2, :field3)
se = Structure_example.new("abc", "xyz", 123)    => #<struct Structure_example filed1="abc", field2="xyz", field3=123>

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.

p se    => #<struct Structure_example filed1="abc", field2="xyz", field3=456>
p se.values    => ["abc", "xyz", 456]
p se.members   => [:field1, :field2, :field3]
Customer = Struct.new(:name, :address)
joe1   = Customer.new("Joe", "adr1")
joe2 = Customer.new("Joe", "adr1")
jane  = Customer.new("Jane", "adr2")
joe1 == joe2      #=> true
joe1.eql?(joe2)   #=> true
joe1.equal?(joe2) #=> false
joe1 == jane      #=> false
print joe1[:name], joe1["name"], joe1[0] # same result in each case  -   => "Joe"

Please see the rdoc for Struct. Add any further examples/tutorials here.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4