简体   繁体   中英

Ruby: Map a function over something if array, do it once if a single object

I'm currently doing this for one of my functions in Ruby:

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

Is there a shorter way of doing "if this is an array, map over and apply the function, if not, then do the function"?

You can just convert a single object into an array. If you are not using the output, each would be better than map as it would not create a new array.

# 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) }

只需使用Array方法,该方法将创建一个包含单个项目的数组,或者仅返回原始数组。

Array(@to_pass).map { |item| do_a_function(item) }

You could transform always to array and make use of flatten, like this:

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

This works because flatten will keep already flattened arrays as they are.

I'd use this:

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

If @to_pass is a single element or an array it will be converted to an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM