Skip to main content
100%

Gist 49850

✓ Published0🌍 Public
DDylanFM
Last edited Jan 21, 2009
Created on Jan 21, 2009

This example demonstrates how to dynamically add instance methods to a Ruby class at runtime using `class_eval` and `define_method`. The code defines a `fun` method that takes a class, a method name, and a block, then injects the block as a new instance method on that class. Specifically, it adds a `world` method to the `String` class, which returns the string `"#{self} world"`. The final line calls `"Hello".world` and outputs `"Hello world"`, showing how the injected method operates on any string instance. The example relies purely on Ruby's core reflection and metaprogramming APIs, with no external libraries or data sources involved.

AI-generated description

Similar vizzes