ARGV in Ruby is an array of arrays?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • talonx
    New Member
    • Mar 2008
    • 18

    ARGV in Ruby is an array of arrays?

    I was under the impression that each element of the ARGV arrays contains a value (non iterable). However, when I run this

    Code:
    def test(args)
    	args.each do |arg|
    		puts arg.respond_to?("each")
    		arg.each do |a|
    			puts a
    		end
    	end
    
    if __FILE__ == $0
    	test(ARGV)
    end
    and run it with ruby test.rb 1 2 3
    I can see that each element is again an array, with one element each.

    Is this expected?
  • improvcornartist
    Recognized Expert Contributor
    • May 2007
    • 303

    #2
    Each element is actually a string, but strings also have a method 'each' so your result is expected. Documentation is here.

    So in your example, ARGV is an array of 3 string elements. Each arg then would be a string. When you do arg.each, it looks at each word within the string.

    Comment

    • talonx
      New Member
      • Mar 2008
      • 18

      #3
      @improvcornarti st: Thanks a lot!
      It's interesting that String.each actually splits it, by default on \n.

      Comment

      Working...