0

I know little about ruby, my following implementation works, but I really feel the approach curbsome

@surfaces = []
Surface.all.each do |surface|
    @surfaces << surface.name
end

the purpose is to extract name value of each surface objects and form them into an array, can anyone tell me the smart way to do this? thanks

1

3 Answers 3

3

You can use Surface.all.collect(&:name).

EDIT: this is equivelent to doing something like this:

Surface.all.collect do |s|
  s.name
end
Sign up to request clarification or add additional context in comments.

2 Comments

thank you, it works like magic. I looked up the method "collect {|item| block } → new_ary", so we pass in a block. But I don't understand the "&:name" part, can you help explain this? thanks
@ChrisChen take a look at my edit and also at meagar's answer
2

Use Enumerable#map to turn one enumerable into another enumerable with a 1-to-1 mapping of elements. Combine with Symbol#to_proc when the mapping involves simply invoking a single method on each element of the input enumerable.

Both of these are equivalent:

@surfaces = Surface.all.map(&:name)

@surfaces = Surface.all.map do |surface|
  surface.name
end

Comments

1

FYI, collect and map alias to the same internal pattern in Ruby.

Here's the stackflow reference: Difference between map and collect in Ruby?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.