0

为什么这是 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

...当我执行这个脚本时,我得到这个输出......

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

...如果我只是将所有内容放在同一行上就可以了...

$ 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
4

2 回答 2

3

看 ma,没有逗号(或引号):

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

# => ["xyz1-3-l", "xyz1-2-l", "dws-zxy-l", "abcl"] 
于 2013-04-10T02:00:50.987 回答
2

换行符在 Ruby 中很重要。您需要将逗号放在行尾或在换行符之前使用反斜杠来表示该行正在继续(当然,在这种情况下,将逗号移动到下一行有什么意义?)。

于 2013-04-09T23:24:13.697 回答