randuser
randuser

Reputation: 13

Ruby does not recognize times method

I wrote a program to simulate the rolling of polyhedral dice but every time I run it I get the error shown below. It displays my prompts and lets me input my numbers, but after that it screws up. I've been trying to find a fix online but I only find people talking about different problems with the times method being undefined. I'm new to Ruby, so any help would be appreciated.

My program:

p = 0
while p < 1
puts "Choose your die type"
die_type = gets.chomp

puts "Choose your number of die"
die_number = gets.chomp

total = 0
i = 1

die_number.times do
  random_int = 1 + rand(die_type)
  total += random_int
  i += 1
end
puts total
end

The error I get:

/dieroll.rb:13: undefined method 'times' for "5":String (NoMethodError)

Upvotes: 1

Views: 1438

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118289

Change die_number = gets.chomp to die_number = gets.to_i. die_number = gets.chomp, assigns a string to the local variable die_number( Because Kernel#gets gives us a string object). String don't have any method called #times, rather Fixnum class has that method.

Change also die_type = gets.chomp to die_type = gets.to_i, to avoid the next error waiting for you, once you will fix the first one.

1.respond_to?(:times) # => true
"1".respond_to?(:times) # => false

In you case die_number was "5", thus your attempt "5".times raised the error as undefined method 'times' for "5":String (NoMethodError).

Upvotes: 2

Related Questions