Experts-
I’m attempting to use the downto method to count down from a variable integer to 1. In the example that follows, sp_num was previously given the value of 2. However, when I run the code, I get this error:
undefined method 'downto' for "2":String (NameError)
Here’s the code:
sp_num.downto(1) {|sp_num_step|
do_stuff_here
}
It seems to me I might have to do some sort of string-to-number translation here. I experimented by replacing “sp_num” with “#{sp_num}”, but that just seemed to make a comment out of the line. (I got a parse error further on.)
Help!
Thanks.
-Kurt
Kurt Euler wrote:
sp_num.downto(1) {|sp_num_step|
sp_num.to_i.downto(1) {|sp_num_step|
do_stuff_here
}
Does this help?
BTW, the #{} construct only applies within double-quoted strings and
regexes (oh, and backquotes, and probably something else I forgot).
Experts-
I’m attempting to use the downto method to count down from a variable
integer to 1. In the example that follows, sp_num was previously given
the value of 2. However, when I run the code, I get this error:
undefined method 'downto' for "2":String (NameError)
Here’s the code:
sp_num.downto(1) {|sp_num_step|
do_stuff_here
}
It seems to me I might have to do some sort of string-to-number
translation here. I experimented by replacing “sp_num” with “#{sp_num}”,
but that just seemed to make a comment out of the line. (I got a parse
error further on.)
Help!
Thanks.
-Kurt
Yes, you need string-to-number translation.
sp_num.to_i.downto(1) {…}
should work.
Ruby doesn’t auto-convert between strings and numbers, thankfully.
Note that at least 6 classes support to_i, so the above code is
flexible/dangerous, depending on your point of view and the context.
Cheers,
Gavin