Can someone explain me this Ruby on Rails puzzle?
class Post < ActiveRecord::Base
has_many :comments
end
Post.first.comments.class
=> Array
Array === Post.first.comments
=> false
Array === [ 1 ]
=> true
Can someone explain me this Ruby on Rails puzzle?
class Post < ActiveRecord::Base
has_many :comments
end
Post.first.comments.class
=> Array
Array === Post.first.comments
=> false
Array === [ 1 ]
=> true
Post.first.comments
is a delegator. It does not give you back an Array directly, but if you do anything with it, it turns into one. This is useful because it lets you do stuff like
Post.first.comments.all(:conditions => {:author_name => 'RJH'})
without having to inject those methods into the array object, or extending the Array
class.