Question

I have a program :

Question : Input a number of integer of 2 digit only , and in the out-put it should show the all input values BUT loop should stop on 42 :

example

input

1 2 87 42 99

output

1 2 87

my code

  a = []
 5.times do |i| 
  a[i] =  Integer(gets.chomp)
 end
 a.each do |e|
   break if e == '42'
  puts e
 end
Was it helpful?

Solution

Few things to change. First of all gets will give you a string together with \n at the end, so you need to change it to gets.chomp to remove it.

Now your loop should look like this:

a.each do |e|
  break if e == '42'
  puts e
end

However ruby's array has much butter function which is perfect for what you want:

puts a.take_while {|e| e != '42'}

Additional notes:

  1. Note that it is operating on strings rather than numbers. You might need to validate the input at some point and convert it into integer values.

  2. 5.times do|i| - the |i| bit is obsolete.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top