question about a particular routing

Discussion in 'Ruby' started by gerberdata, Feb 21, 2012.

  1. gerberdata

    gerberdata Guest

    I found this method definition and I was wondering if someone can
    explain it to me or how to use it.

    def [](method)
    self.__send__(method.to_sym)
    rescue NoMethodError
    nil
    end
     
    gerberdata, Feb 21, 2012
    #1
    1. Advertisements

  2. That method allows for conveniently invoking methods by name without
    throwing an error if the method does not exist. You could invoke method
    "foo" by doing obj["foo"] and do not need to worry for NoMethodError -
    you'll just get nil back.

    Oh, and btw "self." is superfluous.

    Kind regards

    robert
     
    Robert Klemme, Feb 21, 2012
    #2
    1. Advertisements

  3. gerberdata

    Mike Austin Guest

    Just want to add that [] can be a bad choice if this is ever used with other classes that define their own [] with other semantics, such as Array (theslice operator). Also, the parameter "method" could probably be named "method_name" to make it less confusing (to equate it with something that sounds like a string.
    But doesn't hurt. It makes it clear that you are acting upon self, not some method in an outer scope.

    Mike
     
    Mike Austin, Feb 21, 2012
    #3
  4. It can hurt:

    $ ruby19 x.rb
    inner
    x.rb:6:in `baz': private method `foo' called for #<X:0x2019cc2c>
    (NoMethodError)
    from x.rb:13:in `<main>'

    $ cat -n x.rb
    1
    2 def foo; puts "outer" end
    3
    4 class X
    5 def bar; foo; end
    6 def baz; self.foo; end
    7 private
    8 def foo; puts "inner" end
    9 end
    10
    11 x = X.new
    12 x.bar
    13 x.baz
    14

    I wouldn't make it a habit to use "send." unless really needed (e.g. for
    setter invocation). It's clear that __send__(method.to_sym) invokes a
    method on self anyway.

    Kind regards

    robert
     
    Robert Klemme, Feb 21, 2012
    #4
  5. gerberdata

    gerberdata Guest

    So I found this in the Twitter gem
    https://github.com/jnunemaker/twitter/blob/master/lib/twitter/base.rb
    and I am still unclear as to what is the alternative to this as it is
    currently written.
     
    gerberdata, Feb 21, 2012
    #5
  6. gerberdata

    Mike Austin Guest

    You got me :) I'm used to Objective-C these days, and forgot that self refers the that specific class instance in this situation.

    Mike
     
    Mike Austin, Feb 22, 2012
    #6
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.