Reputation: 57
Hi i get the error "undefined method" in the exercise 18 although i did it like its written.
class Exercise18_NamesVariablesCodeFunctions
# this one is like your scripts with ARGV
def print_two(*args)
arg1, arg2 = args
puts "arg1: #{arg1}, arg2: #{arg2}"
end
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2)
puts "arg1: #{arg1}, arg2: #{arg2}"
end
# this just takes one argument
def print_one(arg1)
puts "arg1: #{arg1}"
end
# this one takes no arguments
def print_none()
puts "I got nothin'."
end
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()
end
Here's my error:
exercise18_names_variables_code_functions.rb:25:in `<class:Exercise18_NamesVariablesCodeFunctions>': undefined method `print_two' for Exercise18_NamesVariablesCodeFunctions:Class (NoMethodError)
Did you mean? print
from exercise18_names_variables_code_functions.rb:1:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'
I dont understand this error. I defined all the method. When i add self. to all methods it works.
Upvotes: 1
Views: 73
Reputation: 2248
Try Following.
class Exercise18_NamesVariablesCodeFunctions
# this one is like your scripts with ARGV
def print_two(*args)
arg1, arg2 = args
puts "arg1: #{arg1}, arg2: #{arg2}"
end
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2)
puts "arg1: #{arg1}, arg2: #{arg2}"
end
# this just takes one argument
def print_one(arg1)
puts "arg1: #{arg1}"
end
# this one takes no arguments
def print_none()
puts "I got nothin'."
end
a = Exercise18_NamesVariablesCodeFunctions.new
a.print_two("Zed","Shaw")
a.print_two_again("Zed","Shaw")
a.print_one("First!")
a.print_none()
end
Upvotes: 0
Reputation: 10472
The reason is any method call from inside the class is calling the class methods, whereas all the method you defined are instance methods.
As your code is currently written, you can call those methods after defining an instance of the class.
exercises = Exercise18_NamesVariablesCodeFunctions.new
exercises.print_two("Zed","Shaw") #=> "arg1: Zed, arg2: Shaw"
Exercises is an instance of the class itself, and, therefore, have access to the instance methods of that class.
If you want to call the methods as you have currently, you need to change those methods to class methods, but simply adding self.
before the name of each function
def self.print_two(*args)
arg1, arg2 = args
puts "arg1: #{arg1}, arg2: #{arg2}"
end
Now, you will be able to call that method from inside the class.
You can also wrap all of your class methods in a container.
class Test
class << self
def first_method
end
def second_method
end
end
end
Now, any method inside the class << self
is a class method.
Upvotes: 3