0

I wad told to use brackets. I get the following behaviour when using a variable to call a function. From what I've read in the documentation, brackets aren't supposed to make any difference.

I have this:

def pr (arg1, arg2)
  if arg2
    puts arg1
  end
end

This code results in unexpected ',' in front of the false, but without brackets, it works.

for i in 1...4
  pr (i,false)
end

This works:

for i in 1...4 
  pr i,false
end
3
  • In Ruby 2.3+ you should get an error of the form "syntax error, unexpected ',', expecting ')'" which would alert you to a problem. Are you using an older version of Ruby? I know older versions were a lot more permissive here, but the ambiguity caused a lot of problems like what you're seeing.
    – tadman
    Commented Feb 14, 2019 at 2:13
  • Another thing to note is while Ruby has a for, it doesn't normally get used. Instead, consider: 4.times do |i| (zero-indexed) or 1.upto(4) do |i| where you have a lot more control over how things iterate that way.
    – tadman
    Commented Feb 14, 2019 at 2:15
  • Your question is unclear. What does this have to do with global variables? There is not a single global variable in your code, what makes you think the problem is related to global variables? Commented Feb 14, 2019 at 21:42

1 Answer 1

4

You should remove space before brackets and your code will work fine:

#!/usr/bin/ruby

def pr(arg1, arg2)
  if arg2
    puts arg1
  end
end

for i in 1...4
  pr(i, false)
end

Use either space or brackets before arguments list, never both.

1
  • 1
    Thats it. Thank you Commented Feb 14, 2019 at 13:11

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.