A Place for my head

On Ruby, Rails, Concurrency and fiction

Posted in : ruby | No comments

If you have any hopes of becoming a Ruby guru, then regular dose of ruby-talk is a must. In this post, I would try to summarize some of the cool stuffs being discussed on ruby-talk.

  • In Ruby, having method names that contain “-” can be PITA. So David Black and others were quick to point following approach of doing so:

    1
    2
    3
    4
    5
    
    irb(main):002:0> class C
    irb(main):003:1>   define_method("x-y") { puts "Weird method" }
    irb(main):004:1> end
    # At which point, the only way to call it is:
    irb(main):005:0> C.new.send("x-y")   # Weird method

    In other words, it’s not worth the trouble and you should find some
    other solution.

  • Trans asked on ruby-talk, how can we know, which files are loading or requiring this file. Ara pointed following solution:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    p Kernel.requiree('main')
     
    require 'b'
     
    p Kernel.requiree('main')
     
    BEGIN {
      module Kernel
        h = Hash.new
        define_method(:requiree) do |of|
          h[of]
        end
     
        r = method :require
        define_method(:require) do |*a|
          r.call *a
          h[a.first] = caller
        end
      end
    }

    The interesting bit around, should be noted.

    1
    
      r = method :require

    When you call method and pass method name as a parameter, it returns a closure. Although as pointed by someone it breaks “Rubygems”, and above approach shouldn’t be used. Rather, one should use:

    1
    
      alias_method :old_require, :require

Leave a Reply