Reputation: 21
I'm getting an error with the following example when running the program.
The error reads as such:
burger.rb:8:in `initialize': wrong number of arguments (1 for 0) (ArgumentError)
from burger.rb:19:in `new'
from burger.rb:19:in `<main>'
Any help is appreciated for this noob, the code is below:
$toppings = false
class Burger
AVAILABLE_TOPPINGS = ["lettuce", "tomato", "onion", "cheese"]
attr_reader :options
def initialize
@toppings = []
end
def order
print "how many burgers would you like? "
number = gets.chomp
puts "#{number} burgers coming right up boss!"
end
end
burger = Burger.new("lettuce")
burger.order
Upvotes: 1
Views: 2447
Reputation: 20835
As others have said your initializer is expecting no arguments but you're giving it lettuce
. If you're using ruby 2.1 or later I would suggest using keyword arguments:
class Burger
TOPPINGS = %i[lettuce tomato onion cheese]
attr_reader :toppings
def initialize(toppings: [])
@toppings = TOPPINGS & toppings
end
end
This allows you do to Burger.new(toppings: [:lettuce])
which I feel is a lot more readable.
Upvotes: 2
Reputation: 160631
$toppings = false
is code smell. Globals are generally not necessary, and should only be used when you're absolutely sure they're needed. When you're first learning an OO language I think it's better to avoid them and learn about variable scoping.
In this case, you don't use it in your sample code, but you do use:
@toppings = []
(which is again not used elsewhere). It isn't a good idea to name a global variable the same as an instance variable because it's too easy to use one when you mean the other, and introduce a bug.
Upvotes: 0
Reputation: 122503
The error is telling you that the method initialize
expects 0 argument, while you give it 1 ("lettuce"
in Burger.new("lettuce")
).
You need to make initialize
expecting one argument:
def initialize(options)
@toppings = []
@options = options
end
Upvotes: 2