0

just wondering how I would split a string variable up letter by letter and make it an array

my word variable is a randomly selected word from an array of words:

word = $file_Arr[rand($file_Arr.length)]

how would I then split this word into individual letters and add them to an array?

example: if word pulls the word "hello" from $file_Arr how would I make an array like: ["h", "e", "l", "l", "o"] out of my word variable

All I've been able to find online is people doing it with strings they type in and splitting on a comma, but how would I do it from a variable?

2 Answers 2

1

Use String#chars

http://ruby-doc.org/core-2.0.0/String.html#method-i-chars

2.3.1 :009 > "Hello World".chars
=> ["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"]
Sign up to request clarification or add additional context in comments.

2 Comments

That worked perfectly, thanks, any idea how to remove the "\n" off the end? since it's adding an extra character to the array?
flanelman, if your string is str, you can write str.chomp.chars to first remove the newline character.
1

First you can get a random word using sample. Then you can split the word into characters using chars.

irb(main):004:0> ["hi", "there"].sample.chars
=> ["h", "i"]
irb(main):005:0> ["hi", "there"].sample.chars
=> ["t", "h", "e", "r", "e"]

The result is different when called multiple times.

As far as you last question, you should be able to call chars the same way on a variable.

irb(main):006:0> x = "hi"
=> "hi"
irb(main):007:0> x.chars
=> ["h", "i"]

2 Comments

Thanks for the response, this is exactly what I was after! :)
Glad I could help!

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.