0

我目前正在为我在 Ruby 中的一个函数执行此操作:

if @to_pass.kind_of?(Array)
        @to_pass.map do {|item| do_a_function(item)}
    else
        do_a_function(item)
    end

是否有更短的方法来执行“如果这是一个数组,则映射并应用该函数,如果不是,则执行该函数”?

4

4 回答 4

3

Just use the Array method, which will either create an array containing the single item or just return the original array.

Array(@to_pass).map { |item| do_a_function(item) }
于 2013-08-28T17:24:08.527 回答
3

您可以将单个对象转换为数组。如果您不使用输出,则 each 会比 map 更好,因为它不会创建新数组。

# if single object doesn't respond to to_a
# as Guilherme Bernal pointed out in comments, flatten(1) should be used rather than flatten
[@to_pass].flatten(1).each {|item| do_a_function(item) }

# if it does
@to_pass.to_a.each {|item| do_a_function(item) }
于 2013-08-28T17:10:04.893 回答
1

您可以始终转换为数组并使用 flatten,如下所示:

([@to_pass].flatten).map { |item| do_a_function(item) }

这是有效的,因为flatten将保持已经展平的数组不变。

于 2013-08-28T17:12:49.093 回答
0

我会用这个:

[*@to_pass].map{ |e|
  ...
}

如果@to_pass是单个元素或数组,它将被转换为数组。

于 2013-08-28T17:56:59.137 回答