编辑
我最初是想用一句话来表达这一点的,我想说一句话。我已经相应地编辑了这个问题。
假设我有一个返回两项数组的方法,比如颜色和一周中的一天。

def make_tuple
  [['blue', 'red', 'orange'].sample, ['Mon','Wed', 'Fri'].sample]
end
make_tuple # =>  ['orange', 'Wed']

我可以将输出捕获为两个单独的变量,如下所示:
color, day = make_tuple

我可以将这些输出收集到两个单独的集合中,如下所示:
colors ||= []
days   ||= []
colors << color
days   << day

有没有办法将这两个步骤(从元组中获取单独的值并将它们附加到单独的现有集合)组合到一个语句中?例如:
# Doesn't work
colors <<, days << = make_tuple

最佳答案

一些例子,包括函数式和命令式:

def make_tuple
  [['blue', 'red', 'orange'].sample, ['Mon','Wed', 'Fri'].sample]
end

# Functional creation of pairs with N elements
colors, days = 3.times.map { make_tuple }.transpose
#=> [["blue", "blue", "blue"], ["Wed", "Wed", "Mon"]]

# Functional append (creates new arrays)
colors2, days2 = [colors, days].zip(make_tuple).map { |ar, x| ar + [x] }
#=> [["blue", "blue", "blue", "red"], ["Wed", "Wed", "Mon", "Fri"]]

# Imperative append
[colors, days].zip(make_tuple) { |pair, p| pair << p }
#=> [["blue", "blue", "blue", "red"], ["Wed", "Wed", "Mon", "Fri"]]

# Imperative append building an abstraction Array#zip_append
class Array
  def zip_append(items)
    zip(items) { |array, item| array << item }
  end
end

[colors, days].zip_append(make_tuple)
#=> [["blue", "blue", "blue", "red"], ["Wed", "Wed", "Mon", "Fri"]]

关于ruby - 我可以在一个语句中拆分数组并将输出附加到单独的数组吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8624547/

10-12 12:36