在Ruby中处理单个值或数组的最佳方法是什么

时间:2021-12-31 23:18:40

I want to write a method that accepts either a single value or an array. What's the best idiom for doing this in Ruby?

我想编写一个接受单个值或数组的方法。在Ruby中这样做最好的成语是什么?

Here are a couple things I've thought of:

以下是我想到的一些事情:

def do_something(items)
  [*items].each { |item| ... }
end

I like the conciseness of that one, but it isn't clear unless you're used to this syntax

我喜欢那个的简洁,但除非你已习惯这种语法,否则它并不清楚

This next one just feels like too much code.

下一个感觉就像是太多的代码。

def do_something(items)
  items = [items] unless items.respond_to? :each
  items.each { |item| ... }
end

1 个解决方案

#1


3  

The Kernel#Array method works well here and is intended to be used to coerce things to an array:

Kernel#Array方法在这里运行良好,旨在用于将数据强制转换为数组:

irb(main):001:0> def my_length(item_or_array)
irb(main):002:1>   Array(item_or_array).length
irb(main):003:1> end
=> nil
irb(main):004:0> my_length('one')
=> 1
irb(main):005:0> my_length([1, 2, 3])
=> 3

#1


3  

The Kernel#Array method works well here and is intended to be used to coerce things to an array:

Kernel#Array方法在这里运行良好,旨在用于将数据强制转换为数组:

irb(main):001:0> def my_length(item_or_array)
irb(main):002:1>   Array(item_or_array).length
irb(main):003:1> end
=> nil
irb(main):004:0> my_length('one')
=> 1
irb(main):005:0> my_length([1, 2, 3])
=> 3