Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate initializer in Ruby?

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?

like image 453
Chris Xue Avatar asked Apr 30 '12 13:04

Chris Xue


People also ask

What is initializer in Ruby?

The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object.

How do you initialize a variable in Ruby?

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.

What is new () in Ruby?

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.


2 Answers

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
like image 130
Phrogz Avatar answered Sep 30 '22 12:09

Phrogz


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
like image 25
Casper Avatar answered Sep 30 '22 13:09

Casper