开发者

Reflecting on the class of the immediate ancestor

开发者 https://www.devze.com 2022-12-10 06:54 出处:网络
Apple < ActiveRecord:Base Orange < ActiveRecord:Base piece_of_fruit = Apple.new I want to know whether piece_of_fruit is an Apple or an Orange - even though both are derived from ActiveRecord
Apple < ActiveRecord:Base
Orange < ActiveRecord:Base

piece_of_fruit = Apple.new

I want to know whether piece_of_fruit is an Apple or an Orange - even though both are derived from ActiveRecord:Base.

Is there a reflection method that will tell me the next class in the inheritance tree (Apple/Orange).

What about if I want to look at each开发者_StackOverflow successive step in the inheritance hierarchy after that, starting with ActiveRecord:Base in this case?


How about

piece_of_fruit.kind_of?(Apple)


The answer to your first question, as others have posted, is

piece_of_fruit.is_a? Apple

The answer to your second question ("What if I want to look at each successive step in the inheritance hierarchy?") is to use the class and superclass methods.

piece_of_fruit.class 
=> Apple
piece_of_fruit.class.superclass     
=> ActiveRecord::Base


is_a and kind_of are synonymous, so you can write either of the following:

piece_of_fruit.is_a?(Apple)

or

piece_of_fruit.kind_of?(Apple)
0

精彩评论

暂无评论...
验证码 换一张
取 消