How Does This Block Work for Integer Times Method

Ruby .times method called on an integer. How does it know to iterate through each integer as the argument in a block?

The times method actually returns a value, which is the current iterator with every loop it makes (1, 2, 3 ... 100).

The do keyword catches this iterator, and uses it as the variable num.

Anytime you see the num variable, you are seeing the current iterator that's being returned by times.

Integer#times alternative that returns block?

The best answer is in a comment by @LeeJarvis

5.times.map { |x| "text#{x}" }.join

What does Integer#times.collect mean?

It is actually a method from Enumerable, a module that is included in Enumerator.collect acts as a map function you give a block to it and the result is saved in an array for every item in your Enumerable collection.10.times returns an Enumerble object with the numbers from 0 to 10 (non-inclusive).

How do I know what iteration I'm in when using the Integer.times method?

Yes, just have your block accept an argument:

some_value.times{ |index| puts index }
#=> 0
#=> 1
#=> 2
#=> ...

or

some_value.times do |index|
puts index
end
#=> 0
#=> 1
#=> 2
#=> ...

Ruby: How can I properly use `yield` to pass unnamed code block to Integer#times method?

For sake of completeness on this topic, I wanted to demonstrate another technique to call the original block:

def withProc
p = Proc.new
3.times(&p)
end
withProc { print "Go" }

When Proc.new is not given a block, it uses the block that was given to withProc instead. Now you can call p, and it will call the original block. You can also pass p to other methods like times either as a regular argument or as a block argument.

See https://medium.com/@amliving/proc-new-trick-c1df16185599 for more discussion

n.times do block just returns value of n

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

What does the block argument to Array#first do?

You can pass blocks to any method, absolutely any. If it doesn't need the block, it simply won't use it. It is not an error (because block is not one of the arguments. It's a separate input for a method)



Related Topics



Leave a reply



Submit