0

I am having a problem with the following array iteration. I'd like to create an array jt with the phrase "food" and "drink" as can be seen from the output from first command which is constructed from an item that has two global_tags with each tag having a phrase that is, in this case, food or drink. I'm not sure why I get the two embedded arrays as seen in the last line.

1.9.3p392 :043 > m.global_tags.map { |t| puts t.tag.phrase }
drink
food
 => [nil, nil] 
1.9.3p392 :044 > jt=[]
 => [] 
1.9.3p392 :045 > m.global_tags.map { |t| jt << t.tag.phrase }
 => [["drink", "food"], ["drink", "food"]] 
1.9.3p392 :046 >

Also, I'm trying to get shorter syntax. This seems to work but not sure if this is considered ugly in Ruby terms(?)

1.9.3p392 :050 > m.global_tags.map(&:tag).map(&:phrase)
 => ["drink", "food"] 

Thx for help

1
  • I don't think the latter is ugly, as long as you understand it and it doesn't get too convoluted it's fine. Commented May 22, 2013 at 20:10

1 Answer 1

2
  1. You get two embedded arrays as the return value from .map, it's not jt. If you only need side-effects, use .each
  2. This is bad performance-wise because you have to traverse the array two times.

m.global_tags.map { |t| t.tag.phrase } returns the result you want.

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

2 Comments

thx, yeah 1 is right - my mistake. Think I was trying to do something like your suggestion. have to wait like 10 min.
np - glad to know I helped anyway :)

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.