Skip to content

Instantly share code, notes, and snippets.

@caius
Created December 28, 2011 17:26
Show Gist options
  • Select an option

  • Save caius/1528785 to your computer and use it in GitHub Desktop.

Select an option

Save caius/1528785 to your computer and use it in GitHub Desktop.
def output name=((default=true); "caius")
puts "name: #{name.inspect}"
puts "default: #{default.inspect}"
end
output
# >> name: "caius"
# >> default: true
output "avdi"
# >> name: "avdi"
# >> default: nil
@ngauthier

Copy link
Copy Markdown

this is one of the weirdest ruby thing's I've ever seen. I love it.

xoxo @ngauthier

@caius

caius commented Dec 28, 2011

Copy link
Copy Markdown
Author

I love it too, because I can understand how ruby evaluates it (I think.) The default argument is evaluated as ruby, but in the same scope as the method, so setting local variables means they're set for the method as well. And the parenthesis make it one expression, which ruby is fine with. And then it uses the return value of that expression for the default value of the name variable.

@teoulas

teoulas commented Dec 28, 2011

Copy link
Copy Markdown

Wow, really interesting. Never thought about this use case, but kind of makes sense.

@avdi

avdi commented Dec 28, 2011

Copy link
Copy Markdown

Holy crap, look at all the forks! You've created a monster!

@toamitkumar

Copy link
Copy Markdown

@caius @avdi - what is the use case of this trick ?

@avdi

avdi commented Dec 28, 2011

Copy link
Copy Markdown

The only use case I can think of is lulz. I'd never let this through a code review.

@toamitkumar

Copy link
Copy Markdown

@avdi :) I was scratching if I would ever end up using this trick...

@ngauthier

Copy link
Copy Markdown

turbo lulz:

def x y=((return 'lol'); y)
  y
end

trololo @ngauthier

@ngauthier

Copy link
Copy Markdown

also

def x(y=(raise 'i <3 params')); y; end

@skanev

skanev commented Dec 29, 2011

Copy link
Copy Markdown

Don't forget:

def foo(something = (def foo(*); 'bar'; end)) 'qux' end

puts foo(10)  # qux
puts foo      # qux
puts foo(10)  # bar
puts foo      # bar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment