在Ruby中,以某种方式映射数组的最具表现力的方式是什么?某些元素被修改而其他元素未被触及

这是一种直截了当的方式:

old_a = ["a", "b", "c"]                         # ["a", "b", "c"]
new_a = old_a.map { |x| (x=="b" ? x+"!" : x) }  # ["a", "b!", "c"]

省略“单独留下”当然,如果还不够的话:

new_a = old_a.map { |x| x+"!" if x=="b" }       # [nil, "b!", nil]

我想要的是这样的:

new_a = old_a.map_modifying_only_elements_where (Proc.new {|x| x == "b"}) 
        do |y|
          y + "!"
        end
# ["a", "b!", "c"]

在Ruby中有没有一些很好的方法(或者Rails有一些我还没有找到的方便方法)?


感谢大家的回复。虽然你总是说服我最好只使用 map 和三元运算符,但有些人发布了非常有趣的答案!

有帮助吗?

解决方案

我同意地图声明很好。它清晰简单,而且很容易 任何人都可以维持。

如果你想要更复杂的东西,那怎么样?

module Enumerable
  def enum_filter(&filter)
    FilteredEnumerator.new(self, &filter)
  end
  alias :on :enum_filter
  class FilteredEnumerator
    include Enumerable
    def initialize(enum, &filter)
      @enum, @filter = enum, filter
      if enum.respond_to?(:map!)
        def self.map!
          @enum.map! { |elt| @filter[elt] ? yield(elt) : elt }
        end
      end
    end
    def each
      @enum.each { |elt| yield(elt) if @filter[elt] }
    end
    def each_with_index
      @enum.each_with_index { |elt,index| yield(elt, index) if @filter[elt] } 
    end
    def map
      @enum.map { |elt| @filter[elt] ? yield(elt) : elt }
    end
    alias :and :enum_filter
    def or
      FilteredEnumerator.new(@enum) { |elt| @filter[elt] || yield(elt) }
    end
  end
end

%w{ a b c }.on { |x| x == 'b' }.map { |x| x + "!" } #=> [ 'a', 'b!', 'c' ]

require 'set'
Set.new(%w{ He likes dogs}).on { |x| x.length % 2 == 0 }.map! { |x| x.reverse } #=> #<Set: {"likes", "eH", "sgod"}>

('a'..'z').on { |x| x[0] % 6 == 0 }.or { |x| 'aeiouy'[x] }.to_a.join #=> "aefiloruxy"

其他提示

因为数组是指针,所以这也有效:

a = ["hello", "to", "you", "dude"]
a.select {|i| i.length <= 3 }.each {|i| i << "!" }

puts a.inspect
# => ["hello", "to!", "you!", "dude"]

在循环中,确保使用改变对象的方法而不是创建新对象。例如。与 upcase 相比, upcase!

确切的程序取决于您想要达到的目标。用foo-bar的例子很难确定答案。

old_a.map! { |a| a == "b" ? a + "!" : a }

给出

=> ["a", "b!", "c"]

map!修改了接收器,所以 old_a 现在是返回的数组。

您的 map 解决方案是最好的解决方案。我不确定为什么你认为map_modifying_only_elements_where在某种程度上更好。使用 map 更简洁,更简洁,不需要多个块。

一个班轮:

["a", "b", "c"].inject([]) { |cumulative, i| i == "b" ? (cumulative << "#{i}!") : cumulative }

在上面的代码中,您以[]“累积”开头。当您通过枚举器(在我们的例子中是数组,[“a”,“b”,“c”])枚举时,累积以及“当前”和item get传递给我们的块(| cumulative,i |),块的执行结果被赋值给cumulative。我上面所做的是当项目不是“b”时保持累积不变。并附加“b!”累积数组,当它是b时返回它。

上面有一个答案,使用 select ,这是最简单的方法(并记住)。

您可以将 select map 结合使用,以实现您的目标:

 arr = ["a", "b", "c"].select { |i| i == "b" }.map { |i| "#{i}!" }
 => ["b!"]

select 块中,指定元素被“选中”的条件。这将返回一个数组。你可以打电话给“地图”在结果数组上附加感叹号。

如果您不需要旧阵列,我更喜欢地图!在这种情况下因为你可以使用!表示您正在更改数组的方法。

self.answers.map!{ |x| (x=="b" ? x+"!" : x) }

我更喜欢这个:

new_map = self.old_map{ |x| (x=="b" ? x+"!" : x) }

它只有几行,但这里有一个替代它的地狱:

oa = %w| a b c |
na = oa.partition { |a| a == 'b' }
na.first.collect! { |a| a+'!' }
na.flatten! #Add .sort! here if you wish
p na
# >> ["b!", "a", "c"]

在我看来,三元收藏似乎是最好的。

我发现完成此操作的最佳方法是使用 tap

arr = [1,2,3,4,5,6]
[].tap do |a|
  arr.each { |x| a << x if x%2==0 }
end
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top