ruby send respond_to
http://ruby-metaprogramming.rubylearning.com/html/ruby_metaprogramming_2.html
http://galeki.is-programmer.com/posts/183.html
1.3.2 send 
send( ) is an instance method of the Object class. The first argument to send( ) is the message that you're sending to the object - that is, the name of a method. You can use a string or a symbol, but symbols are preferred. Any remaining arguments are simply passed on to the method.
class Rubyist
def welcome(*args)
"Welcome " + args.join(' ')
end
end
obj = Rubyist.new
puts(obj.send(:welcome, "famous", "Rubyists")) # => Welcome famous Rubyists
With send( ), the name of the method that you want to call becomes just a regular argument. You can wait literally until the very last moment to decide which method to call, while the code is running.
class Rubyist
end rubyist = Rubyist.new
if rubyist.respond_to?(:also_railist)
puts rubyist.send(:also_railist)
else
puts "No such information available"
end
In the code above, if the rubyist object knows what to do with :also_railist, you hand the rubyist the message and let it do its thing.
You can call any method with send( ), including private methods.
class Rubyist
private
def say_hello(name)
"#{name} rocks!!"
end
end
obj = Rubyist.new
puts obj.send( :say_hello, 'Matz')
Note:
- Unlike send(), public_send() calls public methods only.
- Similar to send(), we also have an instance method __send()__ of the BasicObject class.
如同其他的OO语言一样,在ruby中,通过给对象发送消息,来完成对象的功能,比如 str.upcase ,就是给str发送upcase的消息,点操作符(.),就是用来给对象发送消息的,str接受到消息,然后执行与消息对应的功能。
但是,某些时候,我们并不知道对象能响应哪些消息,比如下面的代码就会产生错误:
- > obj = Object.new
- > obj.talk
- undefined method 'talk' for #<Object:0x12345678> (NoMethodError)
因为obj对象没法响应talk这个消息,如果使用 respond_to? 这个方法,就可以实现判断对象能否响应给定的消息了:
- obj = Object.new
- if obj.respond_to?("talk")
- obj.talk
- else
- puts "Sorry, object can't talk!"
- end
这样即使obj不能响应talk,也不会使代码产生错误退出,我们也可以应用 respond_to? 方法,根据对象的属性,在程序运行时灵活的控制。
与 respond_to? 相对应,send 方法和点操作符一样,用来给对象发送消息,比如文章开始的 str.upcase ,用 send 可以写成 str.send("upcase"),它们实现的功能是完全相同的,那么为什么还要用send呢?
这是因为,send 发送的消息,在程序运行时是可变的,我们可以根据不同的输入,动态的向对象发送不同的消息。
比如一个图书管理系统,每本书都有诸如作者、出版社、日期、价钱这些,我们要根据用户的输入查询某本书的属性,如果不用send,我们要对程序的输入做一个一个的测试:
- print "Search for: "
- request = gets.chomp
- if request == "writer"
- puts book.writer
- elsif request == "press"
- puts book.press
- elseif request == "date"
- puts book.date
- ......
如果用send方法的话,就简单多了:
- request = gets.chomp
- if book.respond_to?(request)
- puts book.send(request)
- else
- puts "Input error"
- end
这样不用在逐个对用户的输入进行测试,只要查询对象能否相应这个消息,再用send将输入直接发送给对象即可。
通过 respond_to? 和 send 这两个方法,我们可以构造更灵活和稳定的程序。
ruby send respond_to的更多相关文章
- ruby 模块 respond_to
def hi puts 'hi friend' end module Amodule def self.hello puts 'hello friend' end end def rsp(txt) p ...
- Ruby 一些经常使用的细节
1.try 永远不会抛出异常 在 没有的时候 返回 nil province_id = Province.find_by_name(prov).try(:id) 2.find(:first, :con ...
- metasploit--exploit模块信息
Name Disclosure Date Rank Description ---- ...
- 使用Bootstrap Bar来增加Onboarding Progress Bar功能。
git初始代码https://github.com/chentianwei411/at-mentions-with-action-text 首先,开分支onboardingbar. 然后, rails ...
- Kali linux 2016.2(Rolling)中的Exploits模块详解
简单来将,这个Exploits模块,就是针对不同的已知漏洞的利用程序. root@kali:~# msfconsole Unable to handle kernel NULL pointer der ...
- 【ruby】ruby基础知识
Install Ruby(安装) For windows you can download Ruby from http://rubyforge.org/frs/?group_id=167 for L ...
- Ruby基础类型,动态特性,代码块
#Ruby内置基础数据类型 NilClass,TureClass,FalseClass,Time,Date,String,Range,Struct,Array,Hash #Numerice 1.分为I ...
- Ruby学习之动态调用
作为一个动态语言,对象中的方法不会像静态语言一样需要验证确实存在,动态语言的对象之间一直保持着交谈,如果你调用一个不曾定义过的方法,程序也不会马上就报错而无法运行,只有当运行到你调用这个方法时,解释器 ...
- ruby技巧001:求md5散列
ruby核心库中未包含md5之类的功能,不过在其标准库digest中可以方便的使用该功能: = Digest (from ruby core) ---------------------------- ...
随机推荐
- Google地图之OverlayView使用(自定义叠加层)
Google Maps API 第 3 版提供了用于创建自定义叠加层的 OverlayView 类.OverlayView 是一个基类,提供了您在创建叠加层时必须实现的若干方法.该类还提供了一些方法, ...
- Winform下让你的DataGridView控件支持点语法(即显示list中的子对象属性)
前言: 不想看前言的直接去看正文吧!另外文末有彩蛋. DataGridView可以支持多种数据源格式,比如DataTable和List. DataTable没啥特殊的,本身就是一张二维的表,可以和Da ...
- Ubuntu16.04 安装RabbitMQ
转载https://www.cnblogs.com/hongdada/p/7203589.html 安装RabbitMQ 由于rabbitMq需要erlang语言的支持,在安装rabbitMq之前需要 ...
- C语言中续行符“\”说明
把一个预处理指示写成多行要用“\”续行,因为根据定义,一条预处理指示只能由一个逻辑代码行组成. 而把C代码写成多行则不必使用续行符,因为换行在C代码中只不过是一种空白字符,在做语法解析时所有空白字符都 ...
- 【翻译自mos文章】job 不能自己主动执行--这是另外一个mos文章,本文章有13个解决方法
job 不能自己主动执行--这是另外一个mos文章 參考原文: Jobs Not Executing Automatically (Doc ID 313102.1) 适用于: Oracle Datab ...
- iptables清空链的规则
建立iptables时,首先需要情况系统默认的规则(如果有),这样能够保证iptables按照自己的想法运行. iptables -F //清空链规则,但不会情况子链,也不会清空表的默认策略 ip ...
- SQL 创建索引,语法
索引介绍.及原理 主键,唯一索引 聚集索引的关系 当数据库表的数据太过庞大,的时候我们能够通过加入索引的形式解决. 聚集索引:数据的实际存储顺序与我们做索引的顺序是一致的,这样的索引我们将它成为聚集索 ...
- Java项目(5)——单例模式的应用与研究
单例模式是非常别致的一个模式,非常少有人拿它跟其它模式相比,由于,单例模式非常easy,非常特别,作用就是保证一个类有唯一一个实例,并让一个全局变量使得它能被訪问.而保证这个类仅仅被实例化一次的办法就 ...
- mongoose中的versionKey
通过mongoose中的save方法保存记录时document文档默认最后会有一个字段"__v",这个字段表示该文档是否是刚刚创建的,如果是则字段"__v"的值 ...
- 常用的一个cookie 对象,还有path 兼容性问题
//cookievar ck = { getObj:function() { var ck = document.cookie; var obj = {}; if(ck!="" ...