Ruby/Class/singleton method

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Add a singleton method to a instance object

module Greeter
   def hi
      "hello"
   end
end                     # A silly module
s = "string object"
s.extend(Greeter)       # Add hi as a singleton method to s
s.hi                    # => "hello"
String.extend(Greeter)  # Add hi as a class method of String
String.hi               # => "hello"



Add singleton method to a string instance

  sam = ""
  def sam.play(a)
    "this is a test"
  end
  sam.play("song")



Singleton method not copied

s1 = "cat"
def s1.upcase
  "CaT"
end
s1_dup   = s1.dup
s1_clone = s1.clone
s1                    #=> "cat"
s1_dup.upcase         #=> "CAT"  (singleton method not copied)
s1_clone.upcase       #=> "CaT"  (uses singleton method)



Use extend to include a module to create single methods

module Quantifier
  def any?
    self.each { |x| return true if yield x }
    false
  end
  def all?
    self.each { |x| return false if not yield x }
    true
  end
end
 
list = [1, 2, 3, 4, 5]
 
list.extend(Quantifier)
flag1 = list.any? {|x| x > 5 }        # false
flag2 = list.any? {|x| x >= 5 }       # true
flag3 = list.all? {|x| x <= 10 }      # true
flag4 = list.all? {|x| x % 2 == 0 }   # false