Sadik Sikder
Sadik Sikder

Reputation: 21

How to Concatenate strings in Array using Ruby

I have following sveral arrays which each of them consists into a String.

x = ["t", "o", "d", "a", "y"]
y = ["i", "s"] 
z = ["s", "u", "n", "d", "a", "y"]

my output should be like following:

x = [today]
y = [is] 
Z = [sunday]

in together: today is sunday

How can i get expected array using ruby?

Upvotes: 2

Views: 3819

Answers (3)

Practical1
Practical1

Reputation: 678

You can use the .join() method like this:

x = ["t", "o", "d", "a", "y"]
y = ["i", "s"] 
z = ["s", "u", "n", "d", "a", "y"]

x.join()
=> "today"
y.join()
=> "is"
z.join()
=> "sunday"

Then do this:

x.join + y.join + z.join()
=> "todayissunday"

Or combine x, y, z into one array and call join on it, like this:

Array(x + y + z).join
=> "todayissunday"

Upvotes: 0

ray
ray

Reputation: 5552

For final your output,

[x, y, z].map(&:join).join(' ')

Upvotes: 2

Dbz
Dbz

Reputation: 2761

You will want to use the #join(separator) method.

See the official ruby docs for Array#join

Example:

['h', 'e', 'l', 'l', 'o'].join('')
=> "hello"

A good place to start learning the basics of Ruby is at Code Academy.

I also recommend dash for browsing documentation offline!

Upvotes: 4

Related Questions