search
HomeBackend DevelopmentPython TutorialCompilation of Ruby metaprogramming basics study notes

Note 1:
Code contains variables, classes and methods, collectively called language construct.

# test.rb
class Greeting
 def initialize(text)
  @text = text
 end

 def welcome
  @text
 end
end
my_obj = Greeting.new("hello")
puts my_obj.class
puts my_obj.class.instance_methods(false) #false means not inherited
puts my_obj.instance_variables

result =>
Greeting
welcome
@text

Summary:
Instance methods are inherited from the class, and instance variables exist in the object itself.
Both classes and objects are first-class values ​​in Ruby.

Application example:

mongo API for ruby => Mongo::MongoClient

# testmongo.rb
require 'mongo'
require 'pp'

include Mongo

# the members of replcation-set
# test mongodb server version 2.6.0
host = "192.168.11.51"
# The port of members
# If the port is 27017 by default then otherport don't need to assignment
otherport = ""
port = otherport.length != 0 ? otherport : MongoClient::DEFAULT_PORT

opts = {:pool_size => 5, :pool_timeout => 10}
# Create a new connection
client = MongoClient.new(host, port, opts)

# puts client.class
puts client.class.constants
puts client.instance_variables
puts client.class.instance_methods(false)


Output separately

Constant, Instance Attribute, Instance Method

Note 2: Dynamic calling
When you call a method, you are actually sending a message to an object.

class MyClass
 def my_method(args)
  args * 10
 end
end
obj = MyClass.new

puts obj.my_method(5)
puts "**"
puts obj.send(:my_method, 6)

Result:

50
**
60

You can use object#send() instead of dot notation to call the MyClass#my_method() method:

obj.send(:my_method, 6)
The first parameter of the

send() method is the message to be sent to the object, which can be a symbol (:symbol) or a string. The other parameters will be passed directly to the calling method.
The technology that can dynamically decide which method to call is called Dynamic Dispatch.

Note 3: The difference between symbols and strings
1. Symbols are immutable and the characters in the string can be modified.
2. Operations on symbols are faster.
3. Usually symbols are used to represent the names of things.
For example:

puts 1.send(:+, 4) => 5
String#to_sym(),String#intern() => string to symbol
String#to_s(),String#id2name() => symbol to string
"caoqing".to_sym() => :caoqing
:caoqing.to_s() => "caoqing"

The pattern dispatch method is used in dynamic dispatch.

puts obj.class.instance_methods(true).delete_if{ |method_name| method_name !~ /^my/}
result => 
my_method

Note 4: Dynamic Definition
Use the Module#define_method() method to define a method.

class MyClass
 define_method :my_method do |args|
  args * 3
 end
end
obj = MyClass.new
puts obj.my_method(10)

Result: <code><font face="Courier New">30</font><br> 30


Singleton methods allow adding a method to a single object. singleton methods
# test.rb
str = "My name is caoqing."
def str.title&#63;
 self.upcase == self
end

puts str.title&#63;
puts str.methods.grep(/^title&#63;/)
puts str.singleton_methods


Result:
false
title&#63;
title&#63;


Note 5:

The essence of class methods is that classes are objects and class names are constants. Calling methods on a class is the same as calling methods on an object:
obj.my_method
Cla.class_method



Duck Typing: Whether the object can respond to methods, which can be ordinary methods or singleton methods.

The essence of class methods is that they are singleton methods of the class.
def obj.method
 # method body
end

obj can be an object reference, a constant class name or self.
Class Macro

Ruby objects have no attributes, and attributes can be defined using mimicry methods.

A member of the Module#attr_*() method to define the accessor. Class macros are not keywords but methods.
Eigenclass

The singleton method cannot be found and saved in the ancestor chain according to the conventional method. obj is an object that cannot be saved and cannot exist in the class. Otherwise, all instances can share this method.
An object has a unique hidden class, called the object's eigenclass.

Enter eigenclass scope:
class << obj
 code
end

If you want to get a reference to eigenclass, you can return self when leaving the scope:
Appendix:

The difference between class variables, instance variables, class methods and instance methods
@@                                                                                                                                             @                                                                                                                                                     self(?clas,::).method : Class method
method : Instance method

# test.rb
class Foo
 @@var = "lion"
 def self.method01
  puts "cat"
  @name = "cat"
  @@var = "cat"
  puts @name
 end

 def self.method02
  puts "tiger"
  @name = "tiger"
  @@var = "tiger"
  puts @name
 end

 def self.method03
  puts "dog"
  @name = "dog"
  @@var = "dog"
  puts @name
 end

 def putsname
  puts @name
  puts @@var
 end
end

obj = Foo.new
# obj.method01   => (NoMethodError)

obj.putsname   => lion

Foo.method01
Foo.method02
Foo.method03
obj.putsname

Result:

lion
cat
cat
tiger
tiger
dog
dog

dog

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor