Reputation: 1895
Judging by the answers to this question, I expected
@n.times do
"hello"
end
to return a number of "hello"s equal to the value of @n
. However, no matter how I modify the code, my rails console just returns the value of @n
and nothing more. What am I doing wrong?
For example, if I first set @n = 10
, then the result of the code would just be 10
.
Upvotes: 3
Views: 2154
Reputation: 230521
Nope, I don't see how you inferred from those answers that .times
block should return anything. What it does is it runs specified block specified number of times, nothing more. Return values of the block are discarded. Will do if you want to, say, print "hello" to standard output N times or do some other work.
n.times do
puts 'hello'
end
If you expected N copies of "hello" string in an array, then there are other ways to achieve this. For example:
Array.new(n, 'hello')
n.times.map { 'hello' }
# and many others
Upvotes: 8