ardavis
ardavis

Reputation: 9895

Array to individual pieces

I'm trying to collect emails from a group of people using the following:

def representative_email(group)
  group.representatives.collect{ |m|
    rep.User.find(m.user_id)
    rep.email
  }
end

However this is producing results like: ["[email protected]", "[email protected]"]

How can I remove all [] and "" and leave only:

[email protected], [email protected]

In fact, it would be better to replace the comma with a semi-colon as well.

Upvotes: 0

Views: 103

Answers (3)

tadman
tadman

Reputation: 211740

What you're seeing is the "stringified" version of the Array you've created. If you want it formatted in a different manner, you should do something like this when you call it:

emails = representative_email(group).join(';')

You should also be very careful when using find as it can and will throw an ActiveRecord::RecordNotFound exception if it can't find what you're looking for, so you must be prepared to rescue this. I'm not sure what you're trying to do here with the call to User.find seemingly out of place, either.

Upvotes: 1

sawa
sawa

Reputation: 168259

Probably, you saw that though p or inspect. The double quotations are not part of the strings. They are just ways of representing strings literary. And the brackets and the commas represent that they are within an array. They are just there when you see them through p or inspect. If you want to see how they actually look like, use puts.

Upvotes: 2

Amadan
Amadan

Reputation: 198496

def representative_email(group)
  group.representatives.collect{ |m|
    rep.User.find(m.user_id)
    rep.email
  }.join('; ')
end

The result of your function (i.e. the result of Array#collect) is an Array; the brackets and the quotes are artifacts introduced by the way the Array got converted into a String. If you control the conversion process, it generally goes better - in that you know exactly what you receive.

In this case, you can use Array#join which sticks the string representation of an Array together, using the argument String as a glue.

Upvotes: 5

Related Questions