Take a number input, iterate up to the top of a given range and output numbers into a file
I'm hoping to get my Ruby script to start at an inputted number, say 100, and itterate all the way up to the end of the range; 1000. Having all the numbers in between saved to a file.
This is a code I have so far:
#!/usr/bin/env ruby
if ARGV.length ==0;
puts "Enter the start number"
else puts ARGV.size
ARGV.each do |a|
for i in 0..1000 do
puts i;
end
end
end
To run it I'm typing:
ruby increment.rb 100 > increment.txt
However, it ignores the input number and starts at 1开发者_开发问答 regardless.
What am I doing wrong?
It starts at 0 because you're giving it the range 0..1000
, which starts at 0. If you want to use the numeric value of a
as the starting point, use a.to_i
instead of 0.
ARGV is an array and the first argument is stored in ARGV[0] second in ARGV[1] etc
if ARGV[0]
start = ARGV[0].to_i
else
puts "Enter the start number"
start = gets.to_i
end
(start .. 1000).each do |i|
puts i
end
精彩评论