0

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
0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I ma getting the answer same as the input.i have edited my code have a look
how to validate in input for accepting only 2 digit ?
@bindibhatt - yes, when Yyou convert input to integer you need to change '42' to 42. TO validate input you simply need to check whether you got 2 digits or not. I don't know the requirements so you need to decide what to do in such a case. You can check the format of the input with if input =~ /\A\d{1,2}\z/.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.