当前位置:网站首页>Analyzing method and proc in Ruby
Analyzing method and proc in Ruby
2022-07-26 16:13:00 【Flying watermelon】
Ruby is simple in appearance, but is very complex inside, just like our human body. — Matz https://www.ruby-lang.org/en/about
Ruby And Python、Scala similar , Everything is an object (Seeing Everything as an Object) On the basis of , Support functional programming , This means that the function is a first-class member , It can be passed in as a parameter , It can also be returned as a function value .
however ,Ruby Functions in are not as simple as those in other dynamic languages , It provides Method And Proc Two classes to represent the concept of function , For the difference between these two classes, whether it is official documents or Stackoverflow On the problem , The explanations are very vague . In other languages, functions are often used in Ruby But it doesn't work , The reason is still unclear about the difference between these two classes , I hope this article can help you understand Ruby Medium “ function ” Concept , Make it simple , Integrate with other functional languages .
Block-oriented Programming
Ruby The most common form of code block in is neither Proc Neither Method, It is block. such as :
# Traverse Range/Array etc.
(0..10).each do |num|
puts num
end
# Read the file
File.foreach('README.md').with_index do |line, line_num|
puts "#{line_num}: #{line}"
end
# Traversal file
Dir.glob('*.rb') {|ruby_src| puts "found #{ruby_src}"} The above example demonstrates block Two literal quantities of (literal) form , Very convenient and concise . But there's one thing to note ,block just Ruby A grammar icing provided , It is not assigned to a variable . If the custom function needs to call the passed block, Need to adopt yield The way .
# stay Array Class
class Array
def my_each
0.upto(size) do |i|
yield self[i]
end
end
end
%w(a b c).my_each do |item|
puts item
endFunction oriented Proc
block The advantage of is simplicity , But one drawback is that it cannot be reused , Because it doesn't exist block type . But in other languages , Function names can be passed freely , Here's an example Python Example :
def myinc(x):
return x + 1
map(myinc, [1,2,3]) # => [2, 3, 4]
map(myinc, [4,5,6]) # => [5, 6, 7]Ruby What corresponds to it is The process (Proc), Equivalent to the above functions Ruby The code is :
myinc = Proc.new {|num| num + 1}
# Or the following two ways
# myinc = proc {|num| num + 1}
# myinc = lambda {|num| num + 1}
[1,2,3].map(&myinc) The key of the above code is &myinc Medium &, because map A function can be followed by block, So we need to Proc To block.
When
&When the symbol appears in the function parameter list , The following parameters will be changed to Proc, And take the converted parameters as block Passed to the caller . http://stackoverflow.com/a/9429972/2163429
I have a better understanding here, you can refer to :
&stay C In language, it is an address character ,Ruby Function parameters in can be followed by block, Because of this block Not part of the parameter , So there is no name , It is quite natural that block Understood as a memory address ,block_given?Function can check thisblockWhether there is .&myincIt can be understood as taking Proc Send the address of to map function .
[1,2,3].map(myinc)
# This way of writing will report the following errors
# in `map': wrong number of arguments (given 1, expected 0) (ArgumentError)therefore ,Ruby Medium Proc It is equivalent to the functions of other dynamic languages , Here is another example to illustrate
def myfilter(arr, validator)
arr.each do |item|
if validator.call(item)
puts item
end
end
end
myfilter([1,2,3,4], lambda {|num| num > 3}) # Output 4
# Besides , You can also define myfilter when , utilize & Will the last block To Proc
def myfilter(arr, &validator)
arr.each do |item|
if validator.call(item)
puts item
end
end
end
myfilter([1,2,3,4]) {|num| num > 3}
# Output 4proc vs. lambda
As mentioned above ,Proc There are two literal forms :
myinc = proc {|num| num + 1} # And Proc.new Equivalent
myinc = lambda {|num| num + 1}These two forms of Proc There are two differences :
proc The form does not limit the number of parameters ; and lambda The form is strict and consistent
proc Medium return Statement is valid for the caller ; and lambda It only works on itself
Object oriented Method
Ruby Use in def Defined “ function ” by Method type , Designed for object-oriented features , More generally, object-oriented is messaging , By sending different messages to an object , Objects make different responses , This is related to SICP The third chapter The content of coincides .
class Rectangle
def initialize(width, height)
@width = width
@height = height
end
def area
@width * @height
end
end
rect = Rectangle.new 10, 20
# The traditional way
puts rect.area
# Message delivery mode
puts rect.send :areabecause Ruby The Chinese legal name means to invoke , Therefore, it can generally be used with the same name as the method Symbol To express .
puts rect.method(:area)
#<Method: Rectangle#area> Can pass Method Of to_proc Method can Method Turn to functionally equivalent Proc. such as :
def myinc(num)
num + 1
end
[1,2,3].map(&method(:myinc))
# => [2,3,4]
# stay Ruby The functions defined at the top level of the source file belong to Object object , So the above call is equivalent to :
# [1,2,3].map(&Object.method(:myinc))summary
blockby Proc Grammar icing of , For single useProcDesigned for functional programming , Equivalent to functions of other dynamic languagesMethodDesigned for object-oriented , The first parameter of message passing
clarify Method And Proc After the difference , I have to enjoy Ruby Clever language design , Both functional and object-oriented essence . It is really a necessary weapon for programmers .
Reference resources
边栏推荐
- Is CICC Fortune Securities safe? How long does it take to open an account
- 哪本书才是编程领域的“九阴真经”
- Implementation of personalized healthy diet recommendation system based on SSM
- Build resume editor based on Nocode
- 2022年最新西藏建筑施工架子工(建筑特种作业)模拟考试试题及答案
- A comprehensive review of image enhancement technology in deep learning
- 剑指offer专项突击版第11天
- Paper: all models are wrong, but many are useful: all models are wrong, but many are useful: understand the importance of variables by studying a whole class of prediction models at the same time
- 互联网协议
- Taishan Office Technology Lecture: the zoom ratio of word is slightly different from the display
猜你喜欢

spark-streaming状态流之mapWithState
![[physical simulation] the principle and practice of the simplest shape matching](/img/1e/d91ed992bc648d90d0c68bfe541d7e.jpg)
[physical simulation] the principle and practice of the simplest shape matching

Mapwithstate of spark streaming state flow

Kalibr calibration realsensed435i -- multi camera calibration

PAT甲级 1044 Shopping in Mars
![[RCTF2015]EasySQL](/img/68/328ee5cffc8b267b6b0f284eb8db2c.png)
[RCTF2015]EasySQL

互联网协议

Yushenle's learning record: the first project of SOC FPGA -hello world

潘多拉 IOT 开发板学习(RT-Thread)—— 实验17 ESP8266 实验(学习笔记)

2022年最新北京建筑安全员模拟题库及答案
随机推荐
Re9:读论文 DEAL Inductive Link Prediction for Nodes Having Only Attribute Information
Alibaba cloud DMS MySQL cloud database report error, solve!!
PAT甲级 1045 Favorite Color Stripe
API version control [eolink translation]
Is it safe for Guoyuan futures to open an account online? What is the account opening process?
Build resume editor based on Nocode
spark-streaming状态流之mapWithState
C # set different text watermarks for each page of word
A coal mine in Yangquan, Shanxi Province, suffered a safety accident that killed one person and was ordered to stop production for rectification
Bugku login2
如何通过ETL调度工具 TASKCTL 使用作业插件类型调用 kettle作业?
Robot hand eye calibration ax=xb (eye to hand and eye in hand) and plane nine point calibration
初识OpenGL (3)片段着色器(Fragment Shader)
Implementation of SAP ABAP daemon
Paper: all models are wrong, but many are useful: all models are wrong, but many are useful: understand the importance of variables by studying a whole class of prediction models at the same time
绘制漂亮的中学操场轮廓,生成带经纬度数据
PAT甲级 1047 Student List for Course
Google Earth Engine——MERRA-2 M2T1NXAER:1980-2022年气溶胶逐日数据集
PAT甲级 1050 String Subtraction
技术风向标 | 云原生技术架构成熟度模型解读