Saurabh Shrivastava
Saurabh Shrivastava

Reputation: 1484

Ruby: Take input and take it as loop range

a = $stdin.read
for i in 0..(a)
puts "Hi"
end

This is giving syntax error-in ` ': bad value for range (ArgumentError). What should be improved to get output for a=3 as

Hi
Hi
Hi

Upvotes: 0

Views: 109

Answers (3)

vgoff
vgoff

Reputation: 11313

You need an integer to be used, or you get the ArgumentError. This will accept your input and ensure that it can be converted to an Integer. You can read about the Kernel#Integer method for specifics.

a = Integer($stdin.read)
for i in 0..(a)
  puts "Hi"
end

Upvotes: 0

Yu Hao
Yu Hao

Reputation: 122383

The error is because a is a string, you can make it an integer by:

a = a.to_i

Upvotes: 2

Karoly Horvath
Karoly Horvath

Reputation: 96258

You have to convert the string to an integer (.to_i).

Note: prefer to use times:

a.to_i.times { puts "Hi" }

Upvotes: 0

Related Questions