2

I think this is an easy question but I can't seem to wrap my head around it to solve it. I want to create an instance variable from a property of another instance variable. For example:

@posts = Post.find(:all, :conditions => ['day > ?', Date.today], :order => 'day')

I want to get another instance variable that contains all of the dates from the @posts. Is there a way of quickly getting it without having to create a helper/function? Thanks!

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Marco A
  • 109
  • 1
  • 2
  • 10

2 Answers2

3
@posts.map(&:day)

which is a shorthand for

@posts.map do |post|
  post.day
end

The result is an array of the value of each post.day

Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191
0

What Wayne has is a appropriate. I prefer collect instead of map, but they are equivalent.

@dates = @posts.collect{|post| post.day}.uniq

Notice, uniq at the end will give you the unique values.

Candide
  • 30,469
  • 8
  • 53
  • 60