0

我想迭代一个数组,根据一个标准修改它的元素,并希望在每个元素之后插入另一个元素,除了最后一个元素之后。这样做最符合 Ruby 习惯的方式是什么?

def transform(input)
  words = input.split
  words.collect {|w|
    if w == "case1"
      "add that"
    else
      "add these" + w
    end
    # plus insert "x" after every element, but not after the last
  }
end

例子:

transform("Hello case1 world!") => ["add theseHello", "x", "add that", "x", "add theseworld!"]
4

2 回答 2

0
def transform input
  input.split.map do |w|
    [
      if w == 'case1'
        'add that'
      else
        'add these' + w
      end,
      'x'
    ]
  end.flatten[0..-2]
end

这通常会写成:

def transform input
  input.split.map do |w|
    [ w == 'case1' ? 'add that' : 'add these' + w, 'x' ]
  end.flatten[0..-2]
end
于 2013-01-07T21:18:06.047 回答
0

对所需输出做出一些假设并进行编辑:

def transform(input)
  input.split.inject([]) do |ar, w|
    ar << (w == "case1" ? "add that" : "add these" + w) << "x"
  end[0..-2]
end

p transform("Hello case1 world!")

#=> ["add theseHello", "x", "add that", "x", "add theseworld!"]
于 2013-01-07T21:19:14.353 回答