Skip to content

Instantly share code, notes, and snippets.

@elskwid
Created June 5, 2013 07:05
Show Gist options
  • Save elskwid/5712112 to your computer and use it in GitHub Desktop.
Save elskwid/5712112 to your computer and use it in GitHub Desktop.
Fancy ivar subscript syntax
class A
def initialize
@lambda = ->(x) { puts "lambda: #{x}" }
@proc = Proc.new { |x| puts "proc: #{x}" }
@method = method(:_method)
end
def lambda(x)
@lambda[x]
end
def proc(x)
@proc[x]
end
def meth(x)
@method[x]
end
private
def _method(x)
puts "method: #{x}"
end
end
a = A.new
a.lambda("foo")
# => lambda: foo
a.proc("bar")
# => proc: bar
a.meth("baz")
# => method: baz
@elskwid
Copy link
Author

elskwid commented Jun 5, 2013

@supernullset, after giving this a look I remember now where I've seen it. When you described it, I thought there was something special about the subscript/square bracket syntax on ivars. We could also use .call or .() here as well.

@supernullset
Copy link

ah ok. I did not think that this would work with a method definition; interesting.

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