Who can eplain deeply the ruby's methods?

I wants to know the ruby’s methods’ describe,the relationship between
them,also the mechanism(most wants to know).

what are

methods:
public_methods:
protected_methods:
private_methods:

#e.g(from ruby API 1.9.2)

mod.instance_methods(include_super=true) → array
Returns an array containing the names of the public and protected
instance methods in the receiver. For a module, these are the public and
protected methods; for a class, they are the instance (not singleton)
methods. With no argument, or with an argument that is false, the
instance methods in mod are returned, otherwise the methods in mod and
mod‘s superclasses are returned.

mod.public_instance_methods(include_super=true) → array
Returns a list of the public instance methods defined in mod. If the
optional parameter is not false, the methods of any ancestors are
included.

mod.protected_instance_methods(include_super=true) → array
Returns a list of the protected instance methods defined in mod. If the
optional parameter is not false, the methods of any ancestors are
included.

mod.private_instance_methods(include_super=true) → array
Returns a list of the private instance methods defined in mod. If the
optional parameter is not false, the methods of any ancestors are
included.


obj.singleton_methods(all=true) → array
Returns an array of the names of singleton methods for obj. If the
optional all parameter is true, the list will include methods in modules
included in obj. Only public and protected singleton methods are
returned.

what’s the relationship between these methods?
#e.g.
String.instance_methods == “str”.methods #true
String.methods(false) == String.singleton_methods(false) #true
class method is the singleton method?


I wants to know the ruby’s methods’ describe,the relationship between
them,also the mechanism(most wants to know).

who can Explain?
thanks…

It’s an object oriented inheritance hierarchy of abstract data types.

For example run this in irb:

String.new.class

then

String.class.ancestors

This will give you an array which is the inheritance chain all the way
down to BasicObject which for most abstract data types is the root
with the exceptions of NilClass, TrueClass, and FalseClass.

The function *_methods are to aid in reflective programming and keep
track of specific function types to that class( or object for
singletons). Grep can be used to search the object path in the case of
function overloading one can call super which may open up alternative
ways to deal with message passing, signals and polymorphism.

The simplest way to “see” this is to start with your base class. In
this case BasicObject and see what methods are in there. From there
move up the line. Some of the data types break off in a tree like
structure but share the common functions as you move up the tree.

In when the same functions are needed they are overwritten in a top
level class to deal with the data types special need. This can be seen
more simply by looking at Float and Integer:

3.14.class.ancestors
=> [Float, Numeric, Comparable, Object, Kernel, BasicObject]

42.class.ancestors
=> [Fixnum, Integer, Numeric, Comparable, Object, Kernel, BasicObject]

Fixnum is ruby’s way of dealing with small numbers( Bignum is it’s
analogue) but ignore that for now as they are both branch off the same
concept of integers. Notice both Float and Integer classes share
Numeric and Comparable. Both inherit from the same common set of
rules. Then somewhere in each respective top level class they overide
those rules as needed to provide common syntax and function they
share. In object oriented speak this is polymorphism.

Another great example would be Array and Hash. Both share Enumerable
and I’m sure both override the .each method to deal with the
abstraction of an indexed array is an associative one. In the end they
are just containers data structures that are pure abstracted and
feature endowed linked lists.

This saves us calls to self and dealing with reverse Hungarian
notation styled function names since ruby’s methods and aliases are
well thought out and can be used as a template or standard to follow
in your own classes you create with them.

Hope that helps you a bit

~Stu

To see what methods are associated with what class which is not
inherited use this syntax:

object.public_methods(false)

examples:

BasicObject.public_methods(false)
=> [:allocate, :new, :superclass, :to_yaml]

class MyClass; def hello; “world”; end; end
x = MyClass.new
=> #MyClass:0x00000002d55618
ruby-1.9.2-head :085 > x.public_method(false)

x.public_methods(false)
=> [:hello]

{}.public_methods(false)
=> [:rehash, :to_hash, :to_a, :inspect, :to_s, :==, :[], :hash,
:eql?, :fetch, :[]=, :store, :default, :default=, :default_proc,
:default_proc=, :key, :index, :size, :length, :empty?, :each_value,
:each_key, :each_pair, :each, :keys, :values, :values_at, :shift,
:delete, :delete_if, :keep_if, :select, :select!, :reject, :reject!,
:clear, :invert, :update, :replace, :merge!, :merge, :assoc, :rassoc,
:flatten, :include?, :member?, :has_key?, :has_value?, :key?, :value?,
:compare_by_identity, :compare_by_identity?, :taguri=, :taguri,
:yaml_initialize, :to_yaml]

and so one.

glad to help. I wrote that right before I went to sleep last night. If
I could edit the post (which I can’t) I’d remove my lazy run on
sentences. I’d also rewrite the array/hash explanation to say this:

Another great example would be Array and Hash. Both data types share
Enumerable and I’m sure both override the .each method to deal with
the polymorphism of either being an indexed array or an associative
array. In the end they are just containers. Container data structures
that are purely abstracted and feature endowed linked lists. This
paradigm shift blurs the distinction of Array and Hash through a
clever abstraction which proves Ruby to be absolutely “principle of
least surprise”

*.each example with a simple hash and multidimensional array :

{one: 1, two:2}.each {|x,y| p x; p y}
:one
1
:two
2
=> {:one=>1, :two=>2}

[[:one,1],[:two,2]].each{|x,y| p x; p y}
:one
1
:two
2
=> [[:one, 1], [:two, 2]]

A better example would be to put both the array and hash into a
variable where one wouldn’t even have to know what the variable data
type was but knew they could parse it without worry of implementation
details or test with a million + one conditionals to figure out how to
deal with the data.

Yukihiro M. truly has engineered an elaborate and eloquent
language which elucidates the intricate nature of object oriented
programming. I can’t begin to explain how much respect I have for this
man.

thank you very much.
your answer is good for me.

Stu wrote in post #994785:

*.each example with a simple hash and multidimensional array :

{one: 1, two:2}.each {|x,y| p x; p y}
:one
1
:two
2
=> {:one=>1, :two=>2}

[[:one,1],[:two,2]].each{|x,y| p x; p y}
:one
1
:two
2
=> [[:one, 1], [:two, 2]]

A better example would be to put both the array and hash into a
variable where one wouldn’t even have to know what the variable data
type was but knew they could parse it without worry of implementation
details or test with a million + one conditionals to figure out how to
deal with the data.

I have just read your questions at this place, i think you are a deep
thinking person.

thank you!~

a) Singleton methods are inserted into an anonymous class immediately
above the object in the method lookup chain.

class Dog
def greet
puts ‘hi’
end
end

d = Dog.new

def d.greet
puts ‘Hello, sir.’
end

d.greet

–output:–
Hello, sir.

b) The methods in an included module are also inserted in an anonymous
class immediately above the class/module that does the include()'ing.

module A
def bark
puts ‘woof’
end
end

module B
def bark
puts ‘meow’
end
end

class Dog
include A
include B

def greet
puts ‘hi’
end
end

Dog.new.bark

–output:–
???

c) One tricky part of the method lookup: class methods are inherited by
subclasses:

class Parent
def self.greet
puts ‘Hi!’
end
end

class Child < Parent
def self.cry
puts ‘Weeep, weep!’
end
end

Child.cry
Child.greet

–output:–
Weeep, weep!
Hi!

7stud – wrote in post #994995:

Thank you 7stud~

savin max wrote in post #994702:

what’s the relationship between these methods?
#e.g.
String.instance_methods == “str”.methods #true

That isn’t a necessary relationship–it just happens to be true in that
case.

  1. methods() returns all the methods that an object will respond to.

  2. instance_methods() returns all the instance methods defined in a
    class, plus all methods that are included in a class, plus all the
    instance methods that are inherited from superclasses(including methods
    that are included by superclasses).

What’s the difference between 1) and 2)?

str = ‘abc’

def str.hello
puts ‘hi’
end

The object str will respond to the :hello message (i.e. you can call
hello() on str). Therefore, hello() will be listed in the array
returned by methods(). However, ‘hello’ is not an instance method
because it was not defined in a regular class or a module. Therefore,
hello() will not be returned by String.instance_methods().

p String.instance_methods.grep(/^h/)

–output:–
[:hash, :hex]

String.methods(false) == String.singleton_methods(false)  #true
class method is the singleton method?

Yes ‘class methods’ are just singleton methods of an object, when the
object is a class. (Can you really call methods() with a false
argument? Of course, I can’t find any ruby documentation on the
methods() method, so who knows?)

class Dog

def initialize(name)
@name = name
end

def do_stuff(other)
puts ‘do_stuff’

my_private_meth()

other.my_protected_meth()

end

protected
def my_protected_meth
puts @name
end

private
def my_private_meth
puts ‘private meth’
end

end

dogA = Dog.new(“7stud”)

puts “methods():”
p dogA.methods

puts “Dog.instance_methods():”
not_inherited = false
p Dog.instance_methods(not_inherited)

puts “Dog.public_instance_methods():”
p Dog.public_instance_methods(not_inherited)

puts “Dog.protected_instance_methods():”
p Dog.protected_instance_methods(not_inherited)

puts “Dog.private_instance_methods():”
p Dog.private_instance_methods(not_inherited)

–output:–
methods():
[:do_stuff, :my_protected_meth, :nil?, :===, :=~, :!~, :eql?, :hash,
:<=>, :class, :singleton_class, :clone, :dup, :initialize_dup,
:initialize_clone, :taint, :tainted?, :untaint, :untrust, :untrusted?,
:trust, :freeze, :frozen?, :to_s, :inspect, :methods,
:singleton_methods, :protected_methods, :private_methods,
:public_methods, :instance_variables, :instance_variable_get,
:instance_variable_set, :instance_variable_defined?, :instance_of?,
:kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?,
:respond_to_missing?, :extend, :display, :method, :public_method,
:define_singleton_method, :id, :object_id, :to_enum, :enum_for, :==,
:equal?, :!, :!=, :instance_eval, :instance_exec, :send]
Dog.instance_methods():
[:do_stuff, :my_protected_meth]
Dog.public_instance_methods():
[:do_stuff]
Dog.protected_instance_methods():
[:my_protected_meth]
Dog.private_instance_methods():
[:initialize, :my_private_meth]

=======

Note that instance_methods() returns both public and protected
methods–but not private methods.

dogA = Dog.new(“7stud”)
dogA.my_private_meth

–output:–
prog.rb:49:in <main>': private methodmy_private_meth’ called for
#<Dog:0x9cf1684 @name=“7stud”> (NoMethodError)

dogA.my_protected_meth

–output:–
prog.rb:49:in <main>': protected methodmy_protected_meth’ called for
#<Dog:0x96546a0 @name=“7stud”> (NoMethodError)

dogB = Dog.new(“savin”)
dogA.do_stuff(dogB)

–output:–
do_stuff
private meth
savin

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs