Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "for" in Ruby

Tags:

In Ruby:

for i in A do     # some code end 

is the same as:

A.each do |i|    # some code end 

for is not a kernel method:

  • What exactly is "for" in ruby
  • Is there a way to use other keywords to do similar things?

Something like:

 total = sum i in I {x[i]} 

mapping to:

 total = I.sum {|i] x[i]} 
like image 305
David Nehme Avatar asked Sep 30 '08 22:09

David Nehme


People also ask

What is a for loop in Ruby?

A loop is the repetitive execution of a piece of code for a given amount of repetitions or until a certain condition is met. We will cover while loops, do/while loops, and for loops.

What does .times do in Ruby?

The times function in Ruby returns all the numbers from 0 to one less than the number itself. It iterates the given block, passing in increasing values from 0 up to the limit. If no block is given, an Enumerator is returned instead.

What does :: mean in Ruby?

The use of :: on the class name means that it is an absolute, top-level class; it will use the top-level class even if there is also a TwelveDaysSong class defined in whatever the current module is.

How do you break a for loop in Ruby?

In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement. By using break statement the execution will be stopped.


1 Answers

It's almost syntax sugar. One difference is that, while for would use the scope of the code around it, each creates a separate scope within its block. Compare the following:

for i in (1..3)   x = i end p x # => 3 

versus

(1..3).each do |i|   x = i end p x # => undefined local variable or method `x' for main:Object 
like image 54
Firas Assaad Avatar answered Oct 15 '22 19:10

Firas Assaad