0

If I have an array like this:

array = ["A", "P", "P", "L", "E"]

And I would like to use the elements of the array to build a sentence. Like for example "I would like to have an APPLE"

I think I saw something similar being done using the yield method. But not sure how to use that in this scenario.

If I just parse the array to string like this:

the_word = array.to_s

Its still is displayed as a array of strings. ["A", "P", "P", "L", "E"]

So my question is how do I get the elements of the array and formats the elements into a string, without iterating the whole sentence multiple times?

2 Answers 2

4

Use join():

1.9.3-p547 :001 > array = ["A", "P", "P", "L", "E"]
 => ["A", "P", "P", "L", "E"] 
1.9.3-p547 :002 > array.join()
 => "APPLE" 

Or use it without parenthesis (kudos to Anthony's comment):

1.9.3-p547 :003 > array.join
 => "APPLE" 
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you sir, theres alot of handy methods in ruby.
Being able to join an array's elements into a string, using some sort of delimiter or an empty string, is a standard method or function in every language I've ever used, except assembler. So, it's not Ruby that's convenient, it's really the years of language implementors who saw the same need.
Yes you're right, but Ruby seem to do the same task but with less code compared to Java.
You can just do array.join (without the parens - it assumes you want to join with nothing between the elements)
2

There is another method Array#*, called Repetition — With a String argument, equivalent to ary.join(str).

arup@linux-wzza:~> pry
[1] pry(main)> array = ["A", "P", "P", "L", "E"]
=> ["A", "P", "P", "L", "E"]
[2] pry(main)> array * ""
=> "APPLE"
[3] pry(main)>

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.