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:

  1. Unlike send()public_send() calls public methods only.
  2. Similar to send(), we also have an instance method __send()__ of the BasicObject class.

如同其他的OO语言一样,在ruby中,通过给对象发送消息,来完成对象的功能,比如 str.upcase ,就是给str发送upcase的消息,点操作符(.),就是用来给对象发送消息的,str接受到消息,然后执行与消息对应的功能。

但是,某些时候,我们并不知道对象能响应哪些消息,比如下面的代码就会产生错误:

  1. > obj = Object.new
  2. > obj.talk
  3.  
  4. undefined method 'talk' for #<Object:0x12345678> (NoMethodError)

因为obj对象没法响应talk这个消息,如果使用 respond_to? 这个方法,就可以实现判断对象能否响应给定的消息了:

  1. obj = Object.new
  2. if obj.respond_to?("talk")
  3.    obj.talk
  4. else
  5.    puts "Sorry, object can't talk!"
  6. end

这样即使obj不能响应talk,也不会使代码产生错误退出,我们也可以应用 respond_to? 方法,根据对象的属性,在程序运行时灵活的控制。

与 respond_to? 相对应,send 方法和点操作符一样,用来给对象发送消息,比如文章开始的 str.upcase ,用 send 可以写成 str.send("upcase"),它们实现的功能是完全相同的,那么为什么还要用send呢?

这是因为,send 发送的消息,在程序运行时是可变的,我们可以根据不同的输入,动态的向对象发送不同的消息。

比如一个图书管理系统,每本书都有诸如作者、出版社、日期、价钱这些,我们要根据用户的输入查询某本书的属性,如果不用send,我们要对程序的输入做一个一个的测试:

  1. print "Search for: "
  2. request = gets.chomp
  3.  
  4. if request == "writer"
  5.   puts book.writer
  6. elsif request == "press"
  7.   puts book.press
  8. elseif request == "date"
  9.   puts book.date
  10. ......

如果用send方法的话,就简单多了:

  1. request = gets.chomp
  2.  
  3. if book.respond_to?(request)
  4.   puts book.send(request)
  5. else
  6.   puts "Input error"
  7. end

这样不用在逐个对用户的输入进行测试,只要查询对象能否相应这个消息,再用send将输入直接发送给对象即可。

通过 respond_to? 和 send 这两个方法,我们可以构造更灵活和稳定的程序。

ruby send respond_to的更多相关文章

  1. ruby 模块 respond_to

    def hi puts 'hi friend' end module Amodule def self.hello puts 'hello friend' end end def rsp(txt) p ...

  2. Ruby 一些经常使用的细节

    1.try 永远不会抛出异常 在 没有的时候 返回 nil province_id = Province.find_by_name(prov).try(:id) 2.find(:first, :con ...

  3. metasploit--exploit模块信息

    Name                                             Disclosure Date  Rank    Description ----           ...

  4. 使用Bootstrap Bar来增加Onboarding Progress Bar功能。

    git初始代码https://github.com/chentianwei411/at-mentions-with-action-text 首先,开分支onboardingbar. 然后, rails ...

  5. Kali linux 2016.2(Rolling)中的Exploits模块详解

    简单来将,这个Exploits模块,就是针对不同的已知漏洞的利用程序. root@kali:~# msfconsole Unable to handle kernel NULL pointer der ...

  6. 【ruby】ruby基础知识

    Install Ruby(安装) For windows you can download Ruby from http://rubyforge.org/frs/?group_id=167 for L ...

  7. Ruby基础类型,动态特性,代码块

    #Ruby内置基础数据类型 NilClass,TureClass,FalseClass,Time,Date,String,Range,Struct,Array,Hash #Numerice 1.分为I ...

  8. Ruby学习之动态调用

    作为一个动态语言,对象中的方法不会像静态语言一样需要验证确实存在,动态语言的对象之间一直保持着交谈,如果你调用一个不曾定义过的方法,程序也不会马上就报错而无法运行,只有当运行到你调用这个方法时,解释器 ...

  9. ruby技巧001:求md5散列

    ruby核心库中未包含md5之类的功能,不过在其标准库digest中可以方便的使用该功能: = Digest (from ruby core) ---------------------------- ...

随机推荐

  1. 学习WCF笔记之二

    一.学习文章http://www.cnblogs.com/iamlilinfeng/archive/2012/09/25/2700049.html 二.步骤 学习WFC,按照大神的文章一步步学习,不过 ...

  2. ASP.NET CORE 学习之自定义异常处理

    为什么异常处理选择中间件? 传统的ASP.NET可以采用异常过滤器的方式处理异常,在ASP.NET CORE中,是以多个中间件连接而成的管道形式处理请求的,不过常用的五大过滤器得以保留,同样可以采用异 ...

  3. 转multicast vs broadcast

    转自:http://blog.csdn.net/bloghome/article/details/4682984 一.multicast概述:   多媒体应用集成了声音.图形.动画.文本以及视频,这种 ...

  4. 修改TreeList单元格格式(实现类似单元格合并效果)

    关键点:(1)TreeList中显示的单元格默认不显示上.下.左.右边框,显示的是TreeList自身的行横边框.列纵边框,具体对应TreeList属性中OptionView项下的ShowVertLi ...

  5. 采用dlopen、dlsym、dlclose加载动态链接库

    1.前言 为了使程序方便扩展,具备通用性,可以采用插件形式.采用异步事件驱动模型,保证主程序逻辑不变,将各个业务已动态链接库的形式加载进来,这就是所谓的插件.linux提供了加载和处理动态链接库的系统 ...

  6. iOS8开发之iOS8的UIAlertController

    在iOS8之前用UIActionSheet和UIAlertView来提供button选择和提示性信息,比方UIActionSheet能够这样写: UIActionSheet *actionSheet ...

  7. mysql 查询昨天,今天、七天、30天的数据

    主要是时间戳转"1993-01-01 00:00:00"的时间格式,然后和当前时间比对CURDATE() 如果字段本身符合正常时间格式,则直接使用即可 今天的数据 SELECT * ...

  8. 【Android】7.3 GridLayout(网格布局)

    分类:C#.Android.VS2015: 创建日期:2016-02-10 一.简介 Android 4.0(API 14)开始提供的GridLayout布局使用虚细线将布局划分为行.列和单元格,也支 ...

  9. 在Maprecue中利用MultipleOutputs输出多个文件

    用户在使用Mapreduce时默认以part-*命名, MultipleOutputs能够将不同的键值对输出到用户自己定义的不同的文件里. 实现过程是在调用output.write(key, new ...

  10. Cocos2d-x Scene生命周期 pushScene和replaceScene

    最近在开发过程中遇到很多切换场景的时候概率性崩溃,内存暴增的问题.因此总结一些开发中需要注意的要点, 1. 切换全屏场景的时候最好使用replaceScene而不是pushScene. 因为pushS ...