This code form RubyMonk works in RubyMonk:
class Calculator
def add(a, b)
a + b
end
def subtract(a, b)
a - b
end
end
I copied it to Sublime Text 2, set the build system to Ruby, then I saved it. When I type in the console something like add(1, 2)
, I get the following exception:
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'add' is not defined
I couldn't find a solution to this. I tried reinstalling Sublime Text 2, tried the beta of ST3, tried other code which I know to be good (same error), etc., and nothing is working. Any ideas?
EDIT: On the suggestion of another user, I tried:
Calculator.new.add(1, 2)
which returned:
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'Calculator' is not defined
Sublime Text 2 console is python console, not ruby.
Additionally your ruby code is incorrect.
I have the sensation that you're calling the method add(1,2) for no Object at all. What I mean is, in this case, that you're not telling the Calculator to add, but just to the thin air... which does not know how to add!
Try doing th following: Calculator.new.add(1,2)
And you'll be asking an instance of the Calculator to add.
Tell me if you have any doubts or if I'm completely mistaken!
EDIT: As stated by texasbruce, ST2 console is Python. Therefore, the solution is the following: Add puts Calculator.new.add(1,2)
in the code and hit Ctrl+B
to launch Ruby.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.