Skip to content

Instantly share code, notes, and snippets.

@jimweirich
Created November 8, 2012 21:00
Show Gist options
  • Save jimweirich/4041577 to your computer and use it in GitHub Desktop.
Save jimweirich/4041577 to your computer and use it in GitHub Desktop.
Ruby Trivia
class Dog
def wag(tail=my_tail)
tail
end
def my_tail
:dogs_tail
end
end
class Cat
def wag_dog
Dog.new.wag
end
def my_tail
:cats_tail
end
end
puts Cat.new.wag_dog # What is printed here?
# Make a prediction before you try it.
@bf4
Copy link

bf4 commented Nov 8, 2012

I think any confusion stems from the chained Dog.new.wag

If you instead wrote that your cat wagged its dog thusly:

dog = Dog.new
dog.wag

I hope no one would think that the wag method on dog somehow reaches back to it's caller to get a parameter it wasn't passed...

@bf4
Copy link

bf4 commented Nov 8, 2012

  • its

now with lambdas... (ok, I suck at this)

dog = ->{ :dogs_tail }
cat = ->(dog){ dog.call }
devious_kitty = ->(cat,dog) {|cat| cat.call(dog) }
devious_kitty.call(cat,dog)

@mikekreeki
Copy link

Putted even more simply it's all about this:

Foo = Class.new do
  def bar(x=self)
    x
  end
end

Foo.new.bar

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