0

Why is this a syntax error in ruby?

#!/usr/bin/ruby

servers = [ 
            "xyz1-3-l" 
    ,       "xyz1-2-l" 
    ,       "dws-zxy-l" 
    ,       "abcl" 
]

hostname_input = ARGV[0]
hostname = hostname_input.gsub( /.example.com/, "" )
servers.each do |server|
    if  hostname == server then 
            puts "that's the one"
            break
    end
end

... when I execute this script I get this output ...

$ ./test.rb abc1
./test.rb:5: syntax error, unexpected ',', expecting ']'
        ,       "xyz1-2-l" 
         ^
./test.rb:6: syntax error, unexpected ',', expecting $end
        ,       "dws-zxy-l" 
         ^

... if I simply put everything on the same line its ok ...

$ cat test.rb 
#!/usr/bin/ruby

servers = [ "xyz1-3-l" ,        "xyz1-2-l" ,    "dws-zxy-l" ,   "abcl" ]

hostname_input = ARGV[0]
hostname = hostname_input.gsub( /.example.com/, "" )
servers.each do |server|
        if  hostname == server then 
                puts "that's the one"
                break
        end
end
$ ./test.rb dws-zxy-l
that's the one
8
  • 1
    Well that's the error then, no? Where the comma goes? Commented Apr 9, 2013 at 23:06
  • commas go at the end of the line, not at the beginning. Commented Apr 9, 2013 at 23:10
  • You don't need this sort of contortion in Ruby, trailing commas are ignored. Commented Apr 9, 2013 at 23:24
  • @muistooshort: Wait, what? I was about to be shocked to discover that I hadn't noticed in seven years of writing Ruby that trailing commas are ignored in arrays, so I tried writing one without them, and…syntax error. Did you mean something else? Commented Apr 9, 2013 at 23:27
  • @Chuck: Works for me with a = [1,2,3,] and even with newlines mixed in. Or did you do [1,2,3,,]? Commented Apr 9, 2013 at 23:33

2 Answers 2

3

Look ma, no commas (or quotes):

servers = %W[
    xyz1-3-l
    xyz1-2-l
    dws-zxy-l
    abcl
]

# => ["xyz1-3-l", "xyz1-2-l", "dws-zxy-l", "abcl"] 
Sign up to request clarification or add additional context in comments.

Comments

2

Newlines are significant in Ruby. You need to put the comma at the end of the line or use a backslash before your newline to indicate that the line is continuing (of course, in that case, what's the point in moving the comma to the next line?).

1 Comment

leading commas mean you can comment out a line without them being off by one. In the OP's case, training commas will work fine, too, but for things like options hashes, leading comma is nice because then you can delete or comment out the line, without having to edit the lines around it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.