Tips for golfing in Ruby
+2
−0
1 answer
+1
−0
Omitting parens on function calls
You can omit parentheses on function calls in many cases.
foo(bar,baz)
foo bar,baz
This is even true if a function call doesn't have any parameters. (This is because all function calls and property accesses are just methods, by the way.)
puts(gets())
puts gets
This can be especially convenient if a call chain can be rearranged so only the last function takes an argument.
->{gets().split(",")}
->{gets.split ?,}
You can even omit parens in a situation like this. Keep in mind this will become ambiguous in some cases!
puts rand 10 # ok
print rand 10, " things" # bad! tries rand(10, " things")
print rand(10), " things" # ok
Notably, you can't omit parens if you pass an argument and a block to a function.
a.reduce{_1+_2} # ok
a.reduce(0){_1+_2} # ok
a.reduce 0{_1+_2} # not ok
0 comment threads