Reputation: 29
When I try to run this code:
class Message
@@messages_sent = 0
def initialize(from, to)
@from = from
@to = to
@@messages_sent += 1
end
end
my_message = Message.new(chicago, tokyo)
I get an error that tells me that one of my parameters is undefined local variable. I was just trying to create an instance using Message
, and was curious as to why this was not working. I thought this would work as I am calling the class.
Upvotes: 1
Views: 4760
Reputation: 656
The 'undefined local variable' error is showing up because there's no value associated with chicago or tokyo. If you want to just pass them as strings, wrap them in quotation marks instead, like this:
class Message
@@messages_sent = 0
def initialize(from, to)
@from = from
@to = to
@@messages_sent += 1
end
end
my_message = Message.new("chicago", "tokyo")
Upvotes: 1
Reputation: 34338
With your current code, you get this error:
undefined local variable or method `chicago' for main:Object (NameError)
because the way you instantiated the Message
class:
my_message = Message.new(chicago, tokyo)
chicago
and tokyo
are interpreted as variable or method that you did not actually define or declare, that's why you got that error.
I think, you just wanted to pass two string objects (putting chicago
and tokyo
in the quotes) as the arguments of Message.new
call like this:
my_message = Message.new('chicago', 'tokyo')
This will solve your problem.
Hope this makes it clear why you are getting the error and how to solve the problem.
Upvotes: 2