|
|
|
|
|
by shokwave
4896 days ago
|
|
Agreed, instance_eval is definitely disgusting, but this trick scores well on readability, it's no more of a trap than some other Ruby idioms, and it serves a good purpose (robustness!). def foo(bar, baz=(default = true; 'default'))
# it still looks separated from other arguments
if default
puts "#{bar}.times { puts #{baz} }"
else
bar.times { puts baz }
end
end
To anyone who knows more Ruby than I - is there a good reason against that I'm missing? |
|
I probably know less Ruby than you but these are my thoughts.
1) I took me a while to work out what was happening but I finally figured out that the default value is only evaluated when the argument isn't present.
2) If the default value is indicated in the docs it would be wrong for the function to behave differently depending on whether that default was relied on explicitly sent. If you need to know this you are probably doing something wrong elsewhere.