Skip to content

Instantly share code, notes, and snippets.

@mfdeveloper
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save mfdeveloper/68cc6a9246d82e872d80 to your computer and use it in GitHub Desktop.

Select an option

Save mfdeveloper/68cc6a9246d82e872d80 to your computer and use it in GitHub Desktop.
Ruby Structs and sintax for >= 2.0 features of language

Ruby Structs and Ruby 2.0+ features

In this snippets with code ruby, you will see the sintax of create Structs and some Ruby 2.0+ features. The features are showed:

Ruby 2.0+ features

  • **keyargs and labelled params

Structs

Sintax to create structures similar to classes but with some diferences. Structs have a basic initialize that get attributes by params and create a method acessors (getters and setters) by default.

# Structs creates 'a class' with attributes
# passed for your constructor like a symbol.
# This example create a class 'MyClass'
# that inherit from Structured class
class MyClass < Struct.new :attrOne,:attrTwo
end
obj = MyClass.new "test"
puts obj.attrOne
# This second example, the object from
# Struct generate a class, like a first
# example above but with more performance
# improvement, without inheritance
MyOtherClass = Struct.new :param1, :param2 do
# Method with key args param define by ** operator.
# Works only Ruby 2.0+ version
def initialize(*args,**kargs)
if !args.empty?
super args
elsif
kargs.each { |attribute,value| self.send(attribute.to_s+'=',value) }
end
end
end
obj2 = MyOtherClass.new :param1 => "valueOne"
puts obj2.param1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment