rubyscopesingleton-methods

Is it possible in Ruby to add singleton methods to an existing object, using variables in the local scope?


I want to add a singleton method code to the String object b = 'text'. It should be able to refer to the hash a defined in the local scope. But my attempt results in an error:

a = {'code'=>200, 'body'=>'text'}
b = a['body']

def b.code
  return a['code']
end

p b.code 

# => 'code': undefined local variable or method `a' for "text":String (NameError)

How can I make this work?


Solution

  • Adding a singleton method that holds a reference to a local variable isn't idiomatic Ruby, but you can do it. You just have to define the method using a block, and the closure will remember the value of a.

    a = { 'code' => 200, 'body' => 'text' }
    b = a['body']
    
    b.send(:define_singleton_method, :code) { a['code'] }
    
    b.code # => 200