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

来源:互联网 发布:2017淘宝双十一攻略 编辑:程序博客网 时间:2024/05/18 23:57

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.rbobj = Object.newdef obj.hello        "hello world"enddef obj.year        "2016/05/23"endputs "obj's id is #{obj.object_id}"puts "Information : "request = gets.chompif 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.rbobj's id is 21802380Information :PS C:\Users\Administrator\RubyCode> ruby obj.rbobj's id is 22326540Information :hellohello worldPS C:\Users\Administrator\RubyCode> ruby obj.rbobj's id is 22334800Information :year2016/05/23PS C:\Users\Administrator\RubyCode> ruby obj.rbobj's id is 22236380Information :hiNo 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
原创粉丝点击