Ruby object .object_id .respond_to? .send()
obj.rb source code
.object_id
可以获取对象id
,该id
唯一确认一个对象;request = gets.chomp
从命令行得到输入,获取想要执行的方法;.respond_to?("xxx")
查找对象是不是有方法xxx
;.send(xxx)
如果对象obj
有xxx
方法,那么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