Determining type of an object in ruby

前端 未结 5 1160
情书的邮戳
情书的邮戳 2021-01-29 17:46

I\'ll use python as an example of what I\'m looking for (you can think of it as pseudocode if you don\'t know Python):

>>> a = 1
>>> type(a)
&l         


        
5条回答
  •  清歌不尽
    2021-01-29 18:01

    Oftentimes 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)
    

提交回复
热议问题