A
A
Anton Misyagin2015-05-05 00:46:45
ruby
Anton Misyagin, 2015-05-05 00:46:45

How to define a method when initializing an object?

I have a class. How to create a new method on the fly in the initialize method? Those. depending on the initialize input parameters, create and name the method so that it is available on the instance

class Foo
  def initialize x
    if x>0
      def positive
      end
    else
      def negative
      end
    end
  end
end

f = Foo.new 1
f.positive

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Miroshnichenko, 2015-05-05
@sunnmas

Hello, you can do it like this:

class Foo
  def initialize x
    if x>0
       define_singleton_method(:positive) { puts 'positive' }
    else
       define_singleton_method(:negative) { puts 'negative' }
    end
  end
end

Although, as for me, this is a rather strange desire to create methods on the fly in initialize )

R
Renat Ibragimov, 2015-05-05
@MpaK999

define_method :method_name do 
 puts "i'am instance method"
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question