Reputation: 39
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?
Upvotes: 0
Views: 188
Reputation: 1637
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"]
Upvotes: 1
Reputation: 19839
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"]
Upvotes: 1