[Ruby笔记]11.Ruby == .equal? object .object_id .respond_to? .send()

Ruby object .object_id .respond_to? .send()

obj.rb source code

  • .object_id 可以获取对象id,该id唯一确认一个对象;
  • request = gets.chomp 从命令行得到输入,获取想要执行的方法;
  • .respond_to?("xxx") 查找对象是不是有方法xxx ;
  • .send(xxx) 如果对象objxxx方法,那么obj.send(xxx) 相当于 obj.xxx执行;
PS C:\Users\Administrator\RubyCode> more obj.rb
obj = Object.new

def obj.hello
        "hello world"
end

def obj.year
        "2016/05/23"
end

puts "obj's id is #{obj.object_id}"

puts "Information : "
request = gets.chomp

if obj.respond_to?(request)
        puts obj.send(request)
else
        puts "No such inforamtion avaiable."
end

run the code

PS C:\Users\Administrator\RubyCode> ruby obj.rb
obj's id is 21802380
Information :

PS C:\Users\Administrator\RubyCode> ruby obj.rb
obj's id is 22326540
Information :
hello
hello world

PS C:\Users\Administrator\RubyCode> ruby obj.rb
obj's id is 22334800
Information :
year
2016/05/23

PS C:\Users\Administrator\RubyCode> ruby obj.rb
obj's id is 22236380
Information :
hi
No such inforamtion avaiable.

object equal ==

  • 创建两个变量hello1以及hello2,赋同样的值“hello world”
PS C:\Users\Administrator\RubyCode> irb --simple-prompt

>> hello1 = "hello world"
=> "hello world"
>> hello2 = "hello world"
=> "hello world"
  • 使用.object_id查看object id
>> hello1.object_id
=> 22097940
>> hello2.object_id
=> 25810140
  • 使用 == 毕竟是做的判断,输出了true
  • 使用a.equal? b判断是否为同一个对象,输出false
>> hello1 == hello2
=> true

>> hello1.equal? hello2
=> false

reference

《The Well-Grounded Rubyist, Second Edition》
(https://www.manning.com/books/the-well-grounded-rubyist-second-edition)
2.3. The innate behaviors of an object

 ∧_∧  /
 (゚д゚ )/マイアヒ~♪
 |⊃ ⊃\♪マイアフ~♪
 |  | \
 ∪-∪

http://emoji.vis.ne.jp/myahe.htm
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值