Instance specific methods? What did they call in Ruby?

I know that there are "instance methods", "class methods", but what methods are called such types, for example:

s1 = "This is my STRING!"

def s1.m1
  downcase
end

p s1     # => "This is my STRING!"
p s1.m1   # => "this is my string!"

What method is the "m1" method called in the "instance" s1 of the "class"? This is really strange because I did not know that this is possible at all if I try:

s2 = "This is ANOTHER string"
s2.m1 # => Won't work!

What is the point, but not sure if defining methods like m1 for instances in a class is generally useful.

+4
source share
4 answers

They are called single point methods and can be defined as follows:

class Person
  def favorite_meal
    "Big Mac"
  end
end

Fred, Joe = 2.times.map { Person.new }

def Fred.favorite_meal
  "Le Big Mac"
end

Joe.favorite_meal #=> Big Mac
Fred.favorite_meal #=> Le Big Mac

Other ways to define the same singleton method would be:

Fred.define_singleton_method :favorite_meal do "Le Big Mac" end

and

class << Fred
  def favorite_meal
    "Le Big Mac"
  end
end

.


: 2 .

2-. , . fred = Person.new. :

  • , .

  • , , y_support/name_magic, , .

gem install y_support :

require 'y_support/name_magic'

class Dog
  include NameMagic
  def speak; puts "Bow wow!" end
end

Spot, Rover = 2.times.map { Dog.new }

Dog , .

Dog.instances.map { |dog| dog.name } #=> :Spot, :Rover
Dog.instances.names # the simpler way to say the same

( ), , .

1- , def Fred.foobar , . singleton , class << Fred:

module Foo
  def bar; "Fretbar!" end
end

class << Fred
  include Foo
  alias le_favorite favorite_meal
end

Fred.bar #=> Fretbar!
Fred.le_favorite #=> "Le Big Mac"

Fred.define_singleton_method 4- , :

local_var = 42

Fred.singleton_class.class_exec do
  define_method :baz do local_var + 1 end
end

Fred.baz #=> 43

, local_var.

local_var = 32
Fred.baz #=> 33

, , , , .

+4

Singleton Methods.

A example , :

, , , .

, , , Singleton Pattern, .

+2

. :

s1 = "This is my STRING!"

def s1.m1
  downcase
end

klass= s1.singleton_class # => #<Class:#<String:0x902d4e8>>
klass.instance_methods(false) # => [:m1]
s1.method(:m1).owner # => #<Class:#<String:0x902d4e8>>
s1.singleton_methods # => [:m1]

, , m1 , .

singleton (m1) s1, s1. - String. , , , , .

s2.m1 # = > !

s1.

+1
source

"(...), but not sure if defining methods like m1 for instances in a class is generally useful."

This makes this behavior possible:

class Test
  def self.some_meth
  end
end

A test is just an instance of a class, and some_method is added to this particular instance.

p Test.singleton_methods #=> [:some_meth]
0
source

All Articles