dblarons
dblarons

Reputation: 123

How to iterate through Ruby/Rails relation

I have a model, FacebookProfile, that has three columns, a, b and c.

I invoke this object by doing:

@facebook_profile = FacebookProfile.find_by_facebook_id(1)

Then I can access each of the values for the columns a, b and c

@facebook_profile.a # result: 1
@facebook_profile.b # result: 2
@facebook_profile.c # result: 3

If I have an array of items a, b and c, how can I iterate through calling these on @facebook_profile?

My best guess:

my_array = ["a", "b", "c"]
for i in my_array
  puts @facebook_profile.i
end

Expected output: 1, 2, 3

I have seen a way to iterate through all columns, but I have other columns besides a, b and c, so I don't think that will work.

Upvotes: 0

Views: 158

Answers (1)

simonb83
simonb83

Reputation: 108

I think you could use the sendoperator to do something along the lines of

my_array = ["a","b","c"]

for i in my_array
  puts @facebook_profile.send(i.to_sym)
end

Upvotes: 1

Related Questions