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!

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it's been great to me so far =)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.