Calling instance methods from Class methods in ruby
-
24-06-2021 - |
Question
Is this the right way of calling an Instance method from a class method? Here the instance_var is passed with the Name object. I want to invoke func1 from the instance_var object passed to the class method.
I wrote this :
Class Name
def initialize
@name
end
def func1(value)
puts value
end
def self.func2(instance_var,val)
instance_var.func1(val)
end
end
Solution
How do you call func2
?
Your code has a small error. You wrote Class
instead class
. With Class
you get a syntax error.
This code works:
class Name
def func1(value)
puts value
end
def self.func2(instance_var,val)
instance_var.func1(val)
end
end
x = Name.new
Name.func2(x, 12) #12
#or
Name.func2(Name.new, 12) #12
Your
def initialize
@name
end
will create an empty variable @name
. It will never get a value. To assign a value you need:
class Name
def initialize (var)
@name = var
end
end
x = Name.new(:x)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow