Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

splat

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]
like image 952
Yasushi Shoji Avatar asked Jan 24 '17 06:01

Yasushi Shoji


1 Answers

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.

like image 177
mu is too short Avatar answered Nov 05 '22 23:11

mu is too short