user107680
user107680

Reputation: 81

Do I treat this as an array or a hash?

I have two models: class User < ActiveRecord::Base and class Tips < ActiveRecord::Base. If I write:

user.each do |...|

or

tips.each.do |...|

Should I treat either as an array or a hash? How will I know?

I would post the model for user and tips, but they are very long. Any help is appreciated! Thanks in advance!!!

Upvotes: 0

Views: 142

Answers (4)

bpieck
bpieck

Reputation: 288

I think your question can be improved in many ways. If I understood correctly:

You have a class

class User < ActiveRecord::Base
  has_many :tips
  ...
end

class Tip < ActiveRecord::Base
  belongs_to :user
  ...
end

So if you have an instance of class Tip (The class should be singular, unless every instance of this class represents many Tips) - let's call this instance @tip - it belongs_to only one user. So @tip.user will be really this one user - nothing to iterate through (nothing like a Hash or an Array). But the user itself has many tips. So @user.tips is something like an array. Although @user.tips is not an array (just try out in rails console something like:

@user = User.first
@user.tips.class

), it behaves in most cases like an array. If you need a real Array here, you can use

@user.tips.to_a

but in most cases you should stick with the association itself.

Upvotes: 1

BarFooBar
BarFooBar

Reputation: 1136

Objects inheriting from ActiveRecord::Base are ActiveRecord Objects and should be treated as such. A comprehensive list of methods can be found here. You can optionally convert AR objects to arrays (using the .to_a built-in) or hashes (by using your own hash implementation depending on how you want the keys and values)

Upvotes: 1

Mike Robinson
Mike Robinson

Reputation: 8945

Programming languages vary as to their exact meaning of "array" vs. "hash," but Ruby (unlike PHP, say ...) follows Perl:

  • A "hash" is a collection of things, indexed by an arbitrary "key."
  • An "array" is an ordered collection of things, indexed by an integer.

Therefore, "what makes the most sense, for you, in this case?" If "this collection-of-things is naturally 'ordered,' such that the "most comfy" way to think of it is "#1, #2, #3 ...," then a Ruby array would be called for. Whereas, if one would (instead) ordinarily think of, "the entry for 'Tom,' 'Dick,' or 'Harry,'" the best representation would be a hash.

Superficially, since I see no obvious "key," the best answer is probably: an array.

Upvotes: 0

croceldon
croceldon

Reputation: 4595

For what it seems you're trying to do, treat it as an array. In fact, you can do User.all.to_a, and it'll be an array.

Upvotes: 0

Related Questions