Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace a for-loop in Ruby?

Tags:

for-loop

ruby

In Ruby it is bad style to use for-loops. This is commonly understood. A style guide recommended to me: (https://github.com/bbatsov/ruby-style-guide#source-code-layout) says:

"Never use for, unless you know exactly why. Most of the time iterators should be used instead. for is implemented in terms of each (so you're adding a level of indirection), but with a twist - for doesn't introduce a new scope (unlike each) and variables defined in its block will be visible outside it."

The example given is:

arr = [1, 2, 3]

#bad
for elem in arr do
  puts elem
end

# good
arr.each { |elem| puts elem }

I have researched and I can't find an explanation as to how to simulate a for loop that provides an iterating value I can pass to places or perform arithmetic on. For example, with what would I replace:

for i in 0...size do
  puts array1[i]
  puts array2[size-1 - i]
  puts i % 2
end

It's easy if it's one array, but I often need the current position for other purposes. There's either a simple solution I'm missing, or situations where for is required. Additionally, I hear people talk about for as if it is never needed. What then is their solution to this?

Can it be improved? And what is the solution, if there is one? Thanks.

like image 526
Plasmarob Avatar asked Aug 13 '13 17:08

Plasmarob


People also ask

How do you USE FOR loop in Ruby?

Ruby for Loop. Ruby for loop iterates over a specific range of numbers. Hence, for loop is used if a program has fixed number of iterations. Ruby for loop will execute once for each element in expression. Syntax: for variable [, variable ...] in expression [do] code. end.

What is an entry controlled loop in Ruby?

It is also known as Entry Controlled Loop because the condition to be tested is present at the beginning of the loop body. for variable_name [, variable...] in expression [do] # code to be executed end for: A special Ruby keyword which indicates the beginning of the loop.

How many times does Ruby for loop execute in an expression?

Ruby for loop will execute once for each element in expression. Syntax: for variable [, variable ...] in expression [do] code. end. for variable [, variable ...] in expression [do] code end.

How to use multiple Boolean expressions in a until loop in Ruby?

You can also use multiple boolean expressions within the parentheses (Boolean_Expressions) which will be connected through logical operators (&&, ||, !). Ruby until loop will executes the statements or code till the given condition evaluates to true.


2 Answers

If you want to iterate over a collection and keep track of the index, use each_with_index:

fields = ["name", "age", "height"]

fields.each_with_index do |field,i|
  puts "#{i}. #{field}" # 0. name, 1. age, 2. height
end

Your for i in 0...size example becomes:

array1.each_with_index do |item, i|
  puts item
  puts array2[size-1 - i]
  puts i % 2
end
like image 142
meagar Avatar answered Oct 04 '22 18:10

meagar


Don't forget you can do cool things like this too

fields = ["name", "age", "height"]

def output name, idx
  puts "#{idx}. #{name}"
end

fields.each_with_index &method(:output)

Output

0. name
1. age
2. height

You can use this technique as a class or instance method too

class Printer
  def self.output data
    puts "raw: #{data}"
  end
end

class Kanon < Printer
  def initialize prefix
    @prefix = prefix
  end
  def output data
    puts "#{@prefix}: #{data}"
  end
end

def print printer, data
  # separating the block from `each` allows
  # you to do interesting things
  data.each &printer.method(:output)
end

example using class method

print Printer, ["a", "b", "c"]
# raw: a
# raw: b
# raw: c

example using instance method

kanon = Kanon.new "kanon prints pretty"
print kanon, ["a", "b", "c"]
# kanon prints pretty: a
# kanon prints pretty: b
# kanon prints pretty: c
like image 33
Mulan Avatar answered Oct 04 '22 16:10

Mulan