Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 693191
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T02:43:42+00:00 2026-05-14T02:43:42+00:00

I’m re-defining a method in an object in ruby and I need the new

  • 0

I’m re-defining a method in an object in ruby and I need the new method to be a closure. For example:

def mess_it_up(o)
  x = "blah blah"

  def o.to_s
    puts x  # Wrong! x doesn't exists here, a method is not a closure
  end
end

Now if I define a Proc, it is a closure:

def mess_it_up(o)
  x = "blah blah"

  xp = Proc.new {||
    puts x  # This works
  end

  # but how do I set it to o.to_s.

  def o.to_s
    xp.call  # same problem as before
  end
end

Any ideas how to do it?

Thanks.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T02:43:42+00:00Added an answer on May 14, 2026 at 2:43 am

    This works (tested in irb):

    NOTE: This changes only str – not all instances of String. Read below for details as to why this works

    another_str = "please don't change me!"
    str =         "ha, try to change my to_s! hahaha!"
    proc = Proc.new { "take that, Mr. str!" }
    
    singleton_class = class << str; self; end
    
    singleton_class.send(:define_method, :to_s) do
      proc.call
    end
    
    puts str.to_s         #=> "take that, Mr. str!"
    puts another_str.to_s #=> "please don't change me!"
    
    # What! We called String#define_method, right?
    
    puts String           #=>  String
    puts singleton_class  #=>  #<Class:#<String:0x3c788a0>>
    
    # ... nope! singleton_class is *not* String
    # Keep reading if you're curious :)
    

    This works because you are opening str’s singleton class and defining a method there. Because this, as well as the call to Module#define_method, have what some call a “flat scope”, you’re able to access variables that would be out of scope if you used def to_s; 'whatever'; end.

    You may want to check out some of these other “metaprogramming spells” here:

    media.pragprog.com/titles/ppmetr/spells.pdf

    Why does it only change str?

    Because Ruby has a couple interesting tricks up it’s sleeves. In the Ruby object model, a method invocation results in the reciever searching not only it’s class (and it’s ancestors), but also it’s singleton class (or as Matz would call it, it’s eigenclass). This singleton class is what allows you to [re]define a method for a single object. These methods are called “singleton methods”. In the example above, we are doing just that – defining a singleton method name to_s. It’s functionaly identical to this:

    def str.to_s
      ...
    end
    

    The only difference is that we get to use a closure when calling Module#define_method, whereas def is a keyword, which results in a change of scope.

    Why can’t it be simpler?

    Well, the good news is that you’re programming in Ruby, so feel free to go crazy:

    class Object
      def define_method(name, &block)
        singleton = class << self; self; end
        singleton.send(:define_method, name) { |*args| block.call(*args) }
      end
    end
    
    
    str = 'test'
    str.define_method(:to_s) { "hello" }
    str.define_method(:bark) { "woof!" }
    str.define_method(:yell) { "AAAH!" }
    
    puts str.to_s #=> hello
    puts str.bark #=> woof!
    puts str.yell #=> AAAH!
    

    And, if you’re curious…

    You know class methods? Or, in some languages, we’d call them static methods? Well, those don’t really exist in Ruby. In Ruby, class methods are really just methods defined in the Class object’s singleton class.

    If that all sounds crazy, take a look at the links I provided above. A lot of Ruby’s power can only be tapped into if you know how to metaprogram – in which case you’ll really want to know about singleton classes/methods, and more generally, the Ruby object model.

    HTH

    -Charles

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.