Ruby .each失败单个元素 [英] Ruby .each fails for single element

查看:152
本文介绍了Ruby .each失败单个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以做一个很好的遍历数组:

I can iterate through an array just fine doing:

def source_names(packages)
    files = []
    packages.each do |package|
        files << (package + ".ads")
        files << (package + ".adb")
    end
    return files
end

但是只有传入一个数组(或者可能是任何集合).但是,当仅将一个包作为更大的脚本的一部分传递给此方法时,此操作将失败,因为看起来像类型是字符串,而不是数组中的单个元素:

But only so long as an array is passed in (or probably any collection). However this fails when only a single package is passed into this method as part of a greater script, because of what looks like the type being a string, instead of a single element in an array:

在"source_names"中:"Generics.Mathematics"的未定义方法"each":字符串(NoMethodError)

in 'source_names': undefined method 'each' for "Generics.Mathematics":String (NoMethodError)

那么我怎么不介意仅传入一个元素,而该元素仅被识别为字符串?

So how do I have it not care that only a single element is passed in, where it's only recognized as a string?

透明化:我知道字符串不支持数组方法.我的困惑是为什么有时会得到一个数组,而有时却得到一个字符串而不是单个元素数组.

Clairification: I know a string doesn't support array methods. My confusion is why i'm getting an array sometimes, and a string othertimes instead of a single element array.

推荐答案

您遇到了该异常,因为类字符串没有实例方法each:

You got that exception because the class String has no instance method each:

String.instance_methods.include?(:each) #=> false

如果packages是字符串,则需要对仅包含该字符串的数组进行操作.我们可以使用方法内核#Array 写:

If packages is a string need to operate on an array comprised of that string alone. We can use the method Kernel#Array to write:

Array(packages).each do |package|

如果packages是数组,则

Array(packages)将返回packages;如果packages是单个元素(此处为字符串),则将返回[packages].

Array(packages) will return packages if packages is an array and will return [packages] if packages is a single element, here a string.

但是,我认为最好是始终将数组传递给方法,即使该数组包含单个元素也是如此.

I think it's better practice, however, to always pass an array to the method, even when the array contains a single element.

这篇关于Ruby .each失败单个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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