簡體   English   中英

如何在Ruby中替換for循環?

[英]How do I replace a for-loop in Ruby?

在Ruby中,使用for循環是一種糟糕的風格。 這通常被理解。 推薦給我的風格指南:( https://github.com/bbatsov/ruby-style-guide#source-code-layout )說:

“永遠不要使用,除非你確切知道為什么。大部分時間都應該使用迭代器.for是按每個方式實現的(所以你要添加一個間接級別),但有一個扭曲 - 因為沒有介紹新的范圍(與每個范圍不同)和在其區塊中定義的變量將在其外部可見。“

給出的例子是:

arr = [1, 2, 3]

#bad
for elem in arr do
  puts elem
end

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

我已經研究過,我找不到關於如何模擬一個for循環的解釋,該循環提供了一個迭代值,我可以傳遞給場所或執行算術運算。 例如,我將替換什么:

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

如果它是一個陣列很容易,但我經常需要當前位置用於其他目的。 有兩種簡單的解決方案,我很想念,或者在需要的情況。 此外,我聽到人們談論 ,就好像從來沒有需要它。 那么他們的解決方案是什么呢?

可以改進嗎? 什么是解決方案,如果有的話? 謝謝。

如果要迭代集合跟蹤索引,請使用each_with_index

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

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

for i in 0...size例子變成:

array1.each_with_index do |item, i|
  puts item
  puts array2[size-1 - i]
  puts i % 2
end

不要忘記你也可以做這樣的酷事

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

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

fields.each_with_index &method(:output)

產量

0. name
1. age
2. height

您也可以將此技術用作類或實例方法

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

使用類方法的示例

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

示例使用實例方法

kanon = Kanon.new "kanon prints pretty"
print kanon, ["a", "b", "c"]
# kanon prints pretty: a
# kanon prints pretty: b
# kanon prints pretty: c

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM