A nitpick, but... string evals considered harmful!

On Monday 08 September 2008 20:19:18 Phlip wrote:
>    class Narcissus
>      def call_once
>        eval '
>          class Narcissus
>            def call_once
>              raise "nope!"
>            end
>          end'
>      end
>    end

I'd write this as:

class Narcissus
  def call_once
    def call_once
      raise 'nope!'
    end
  end
end

But perhaps the more impressive demos are modifying system classes -- 
re-opening String, for instance -- or eigenclass hacks, or dynamically 
generating functions. I always loved define_method. When you know exactly 
what kind of things are acceptable:

class PunchCard
  %w(fold bend mutilate).each do |action|
    define_method action do
      raise "Don't #{action} me!"
    end
  end
end

And when you don't necessarily know, there's method_missing:

class TwoYearOld
  def method_missing method, *args
    puts "That's MY #{method}!"
  end
end

And Ruby makes it very difficult to build a cheat-proof robot game, as you can 
always start rewriting the other robot:

class MyRobot
  def move
    class << other_robot
      def move
        raise 'Explode!'
      end
    end
  end
end

Of course, it's comforting to know that string evals are there -- having a 
working "eval" is a sign of a truly dynamic language. (Probably makes irb 
easier to write, too!) But there's very few legitimate uses of it anymore, I 
think.