Ruby: How can I kill “warning: `*' interpreted as argument prefix”? [duplicate]

北城余情 提交于 2019-12-12 11:15:27

问题


How can I remove the "warning: `*' interpreted as argument prefix" from the following code?

hash = {"a" => 1,
        "b" => 2,
        "s" => 3,}

if "string".start_with? *hash.keys then
  puts "ok"
else
  puts "ng"
end

When I run the code above, I get:

$ ruby -w /tmp/a.rb
/tmp/a.rb:5: warning: `*' interpreted as argument prefix
ok

What is the best way to fix this warning?

I've tried to put parenthesis around hash like this:

hash = {"a" => 1,
        "b" => 2,
        "s" => 3,}

if "string".start_with? (*hash.keys) then
  puts "ok"
else
  puts "ng"
end

then you get:

$ ruby -w /tmp/a.rb
/tmp/a.rb:5: syntax error, unexpected *
if "string".start_with? (*hash.keys) then
                          ^
/tmp/a.rb:5: syntax error, unexpected ')', expecting '='
if "string".start_with? (*hash.keys) then
                                    ^
/tmp/a.rb:7: syntax error, unexpected keyword_else, expecting end-of-input

And this is the problem described in Why does white-space affect ruby function calls?, and clearly not the way to fix the warning I'm trying to fix.

My ruby version is:

$ ruby --version
ruby 2.3.3p222 (2016-11-21) [x86_64-linux-gnu]

回答1:


If you're going to use method-calling-parentheses then you must avoid putting a space between the method name and the opening parentheses:

if "string".start_with?(*hash.keys)
  puts "ok"
else
  puts "ng"
end

Also, then is rather archaic so we'll pretend that was never there. If there is a space between the method name and the opening parentheses then your parentheses are interpreted as expression-grouping-parentheses and that's where your syntax error comes from.

Once you add the method-calling-parentheses you remove any possible hint of ambiguity as to what your * is supposed to mean and the warning should go away.


BTW, the warning you're getting in this case is rather, um, silly. On second thought, the warning isn't so silly because Ruby can be whitespace sensitive in surprising ways. This:

o.m *x

can be interpreted as:

o.m(*x)

or as:

o.m() * x

but these:

o.m * x
o.m*x
o.m* x

can be interpreted in the same ways. Of course, all three of those are interpreted as o.m() * x and only o.m *x is seen as o.m(*x). Sane whitespace usage would suggest that o.m *x is obviously a splat whereas o.m * x is obviously a multiplication but a couple days on SO should convince you that whitespace usage is hardly sane or consistent.

That said, -w's output in the Real World tends to be so voluminous and noisy that -w is nearly useless.



来源:https://stackoverflow.com/questions/41821628/ruby-how-can-i-kill-warning-interpreted-as-argument-prefix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!