Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

arrays - Ruby .each fails for single element

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:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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|

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...