Ruby-将变量优雅地转换为数组(如果还没有数组的话) [英] Ruby - elegantly convert variable to an array if not an array already

查看:56
本文介绍了Ruby-将变量优雅地转换为数组(如果还没有数组的话)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个数组,单个元素或nil,获得一个数组-后两个分别是单个元素数组和一个空数组.

Given an array, a single element, or nil, obtain an array - the latter two being a single element array and an empty array respectively.

我错误地认为Ruby可以这样工作:

I mistakenly figured Ruby would work this way:

[1,2,3].to_a  #= [1,2,3]     # Already an array, so no change
1.to_a        #= [1]         # Creates an array and adds element
nil.to_a      #= []          # Creates empty array

但是您真正得到的是:

[1,2,3].to_a  #= [1,2,3]         # Hooray
1.to_a        #= NoMethodError   # Do not want
nil.to_a      #= []              # Hooray

因此,要解决此问题,我要么需要使用另一种方法,要么可以通过修改我打算使用的所有类的to_a方法来进行元编程-这对我来说不是一个选择.

So to solve this, I either need to use another method, or I could meta program by modifying the to_a method of all classes I intend to use - which is not an option for me.

这是一种方法:

result = nums.class == "Array".constantize ? nums : (nums.class == "NilClass".constantize ? [] : ([]<<nums))

问题在于它有点混乱.有没有一种优雅的方法可以做到这一点? (如果这是解决该问题的类似Ruby的方法,我会感到惊讶)

The problem is that it is a bit of a mess. Is there an elegant way of doing this? (I would be amazed if this is the Ruby-ish way to solve this problem)

在Rails的ActiveRecord中,调用说user.posts将返回一组帖子,单个帖子或nil.当编写根据此结果工作的方法时,最容易假设该方法将采用一个数组,该数组可能具有零个,一个或多个元素.示例方法:

In Rails' ActiveRecord, calling say, user.posts will either return an array of posts, a single post, or nil. When writing methods which work on the results of this, it is easiest to assume that the method will take an array, which may have zero, one, or many elements. Example method:

current_user.posts.inject(true) {|result, element| result and (element.some_boolean_condition)}

推荐答案

[*foo]Array(foo)在大多数情况下都可以使用,但是在某些情况下,例如哈希,会弄乱它.

[*foo] or Array(foo) will work most of the time, but for some cases like a hash, it messes it up.

Array([1, 2, 3])    # => [1, 2, 3]
Array(1)            # => [1]
Array(nil)          # => []
Array({a: 1, b: 2}) # => [[:a, 1], [:b, 2]]

[*[1, 2, 3]]    # => [1, 2, 3]
[*1]            # => [1]
[*nil]          # => []
[*{a: 1, b: 2}] # => [[:a, 1], [:b, 2]]

我认为即使是哈希也可以使用的唯一方法是定义一个方法.

The only way I can think of that works even for a hash is to define a method.

class Object; def ensure_array; [self] end end
class Array; def ensure_array; to_a end end
class NilClass; def ensure_array; to_a end end

[1, 2, 3].ensure_array    # => [1, 2, 3]
1.ensure_array            # => [1]
nil.ensure_array          # => []
{a: 1, b: 2}.ensure_array # => [{a: 1, b: 2}]

这篇关于Ruby-将变量优雅地转换为数组(如果还没有数组的话)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆