Rob Rob - 2 months ago 7
Ruby Question

Ruby: Filter Non-Integers from String

Trying to solve this question where you provide arguments and need to provide a matching output.


Take two integers (i and n) as command line arguments. Write i to standard output, followed by the following n integers (separated by commas).

Do not include spaces or any hidden characters in the output.


Example: Arguments: 3 5 Output: 3,4,5,6,7,8



Here's my code:

base_number = ARGV.shift.to_i
iterate_number = ARGV.shift.to_i

if iterate_number < 0
base_number = base_number.to_s
iterate_number = iterate_number.to_s
else
print base_number
iterate_number.times do
base_number = base_number + 1
print ','
print base_number
end
end


So far, I've managed to catch 7 / 9 of the tests. This includes when iterate_number is negative, which the output returns blank.

The last two tests involve arguments which are letters or blank, both which resolve in the variable i returning 0, giving my output to be 0 instead of blank.

Thanks!

Answer

You're on the right track with times, but you're missing out on one of the key features in Ruby: Leveraging an Enumerator and treating it like an array.

For example:

i = ARGV[0].to_i
n = ARGV[1].to_i

puts (i..i+n).to_a.join(', ')

This sets up a simple range, converts it to an array of values, then joins those values together.

If you want to test if a value is "numerical", try this:

value.to_i.to_s == value

If it's the same when converted to an integer and back it's guaranteed to be an integer value.