ruby中类的实例变量前面需要加@
类变量前面需要加@@
全局变量前需要有$
默认情况下变量是被隐藏的需要使用 attr_read attr_write attr_accessor
attr_accessor :foo
just generates def foo; @foo; end
and def foo=(val); @foo = val; end
a = A.new
a.instance_variables #=> []
a.ab = 'foo'
a.instance_variables #=> [:@ab]
p 1.instance_of? Fixnum #=> True
p "1".instance_of? String #=> True
p [1,2].instance_of? Array #=> True
object.class
.
Since classes can inherit from other classes, if you want to determine if an object is "of a particular type" you might call object.is_a?(ClassName)
to see if object
is of type ClassName
ftentimes in Ruby, you don't actually care what the object's class is, per se, you just care that it responds to a certain method. This is known as Duck Typing and you'll see it in all sorts of Ruby codebases.
So in many (if not most) cases, its best to use Duck Typing using #respond_to?(method)
:
object.respond_to?(:to_i)