Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...