It's time to make it shorter:
class Foo
attr_accessor :a, :b, :c, :d, :e
def initialize(a, b, c, d, e)
@a = a
@b = b
@c = c
@d = d
@e = e
end
end
We have 'attr_accessor' to generate getters and setters.
Do we have anything to generate initializers by attributes?
The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object.
Global variables start with dollar sign like. For Instance Variables: Instance variables can be initialized with @ symbol and the default value for it will be nil.
Creating Objects in Ruby using new Method You can create objects in Ruby by using the method new of the class. The method new is a unique type of method, which is predefined in the Ruby library. The new method belongs to the class methods.
Easiest:
Foo = Struct.new( :a, :b, :c )
Generates both accessors and initializer. You can further customize your class with:
Foo = Struct.new( … ) do
def some_method
…
end
end
We can create something like def_initializer
like this:
# Create a new Module-level method "def_initializer"
class Module
def def_initializer(*args)
self.class_eval <<END
def initialize(#{args.join(", ")})
#{args.map { |arg| "@#{arg} = #{arg}" }.join("\n")}
end
END
end
end
# Use it like this
class Foo
attr_accessor :a, :b, :c, :d
def_initializer :a, :b, :c, :d
def test
puts a, b, c, d
end
end
# Testing
Foo.new(1, 2, 3, 4).test
# Outputs:
# 1
# 2
# 3
# 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With