Ruby/Reflection/Method Reflection

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

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

Содержание

Getting a Reference to a Method

s = "A string"
length_method = s.method("length") # => #<Method: String#length>
length_method.arity                # => 0
length_method.call                 # => 8
p 1.method(:succ).call                # => 2
p 5.method("+").call(10)              # => 15
p [1,2,3].method(:each).call { |x| puts x }
# 1
# 2
# 3



Listing Methods Unique to an Object

class Object
  def my_methods_only
    my_super = self.class.superclass
    return my_super ? methods - my_super.instance_methods : methods
  end
end
p s = ""
p s.methods.size                              # => 143
p Object.instance_methods.size                # =>  41
p s.my_methods_only.size                      # => 102
p (s.methods - Object.instance_methods).size  # => 102



Method pointer

s = "sample string"
replacements = { "a" => "i", "tring" => "ubstitution" }
replacements.collect(&s.method("gsub"))
# => ["simple string", "sample substitution"]



query almost any object within Ruby for the methods that are defined within it

a = "This is a test"
puts a.methods.join(" ")



Sort all method from Object

puts Object.methods.sort
# => ["<", "<=", "<=>", "==", "===", "=~", ">", ">=",
#     "__id__", "__send__", "allocate", "ancestors", ... ]