0
people = [
    {id: 101, first_name: 'John', last_name: 'Doe'},
    {id: 102, first_name: 'Tom', last_name: 'Rogers'},
    {id: 103, first_name: 'Bill', last_name: ''}
]

I want to put a list of name like this

"John Doe, Tom Rogers, Bill"

How can i achieve this is in ruby?

1
  • Please share what you have tried so far. Then we can see where you fall short. Commented Jun 4, 2021 at 12:03

3 Answers 3

1

Input

people = [
  { id: 101, first_name: 'John', last_name: 'Doe' },
  { id: 102, first_name: 'Tom', last_name: 'Rogers' },
  { id: 103, first_name: 'Bill', last_name: '' }
]

Code

p people.map { |x| x[:first_name].to_s + ' ' + x[:last_name].to_s }
        .map(&:strip)
        .join(",")

Output

"John Doe,Tom Rogers,Bill"
Sign up to request clarification or add additional context in comments.

Comments

0

The other answers are good, but I wanted to add a demonstration of string interpolation.

people
  .map { |p| "#{p[:first_name]} #{p[:last_name]}" }
  .join(", ")

@rajagopalan has a good idea in using strip to remove unwanted whitespace at the beginning and end of the first and last name combination, but it might be even better to run this on each component of the name.

people
  .map { |p| "#{p[:first_name].strip} #{p[:last_name].strip}" }
  .join(", ")

4 Comments

"It might be even better to run this on each component of the name". Not really because the last entry in the example would look like this then: "Bill " (Note the whitespace at the end).
Good point. Then maybe the right answer is to do both!
Or perhaps "#{p[:first_name]} #{p[:last_name]}".sub(/\s+/, ' ').strip to remove leading or trailing whitespace, and any extraneous whitespace inside each name.
Extraneous whitespace. .sub(/\s+/, ' ') is going to replace one or more whitespace characters with a single space.
0

I would do

people
  .map { |p| p.values_at(:first_name, :last_name).join(' ').strip }
  .join(', ')
#=> "John Doe, Tom Rogers, Bill"

or

people
  .map { |p| "#{p[:first_name]} #{p[:last_name]}".strip }
  .join(', ')
#=> "John Doe, Tom Rogers, Bill"

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.