0

I'm using Rails 3.2. Here's my code:

transports = %w(car bike)

transports.each do |transport|
  @transport = transport.classify.all
end

That code is not working, but I want the results to be:

@cars = Car.all
@bikes = Bike.all

How do I do that?

1 Answer 1

5
transports.each do |transport|
  instance_variable_set("@#{transport}", 
                        transport.classify.constantize.all)
end

Update Given that the entries in the transports array are now singular the correct code to get the result you want is

transports.each do |transport|
  instance_variable_set("@#{transport.pluralize}", 
                        transport.classify.constantize.all)
end
Sign up to request clarification or add additional context in comments.

2 Comments

If you change transport.classify.all to transport.classify.constantize.all, your answer will be correct. classify does not get the class constant. Also, you will not need to pluralize the transport string, since it is already in plural form.
Many many thanks. Can I post a follow-up question: stackoverflow.com/questions/16555660

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.