redefining a single ruby method on a single instance with a lambda

后端 未结 3 2133
半阙折子戏
半阙折子戏 2020-12-04 18:30

In Ruby, is there a way to redefine a method of a particular instance of a class using a proc? For example:

class Foo
  def bar()
    return \"hello\"
  end         


        
3条回答
  •  独厮守ぢ
    2020-12-04 18:53

    I'm not sure what version of Ruby this was added in (at least 1.8.7), but there seems to be an even simpler way of doing this:

    str1 = "Hello"
    str2 = "Goodbye"
    def str1.to_spanish
      "Hola"
    end
    puts str1 # => Hello
    puts str1.to_spanish # => Hola
    puts str2 # => Goodbye
    puts str2.to_spanish # => Throws a NoMethodError
    

    Learnt about this whilst reading the Ruby Koans (about_class_methods.rb lesson). I'm still not entirely sure what the purpose of this is since it seems a bit dangerous to me.

提交回复
热议问题