Joe Morano
Joe Morano

Reputation: 1895

"n.times do" block just returns value of n

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

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

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

archana
archana

Reputation: 1272

You are not printing anything. Try:

@n.times do
  puts "hello"
end

Upvotes: 2

Related Questions