class

Struct

v1_8_7_72 - Show latest stable - Superclass: Object

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).

Included modules

  • Enumerable

Files

  • lib/pp.rb
  • lib/yaml/rubytypes.rb
  • struct.c

3Notes

Example

marcelo_murad · Jun 30, 20094 thanks

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

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

More Examples

waseem_ · Feb 12, 20122 thanks

=== Code

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

user = User.new("Matz", 43, "male")

Passing a block with methods

tinogomes · Jan 28, 20111 thank

==== Code example

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

def longitude
  -2
end

def with_address
  "with #{address}"
end
end

g = Google.new("Some Addres")

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

==== Result

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