Answer the question
In order to leave comments, you need to log in
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
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question