Reputation: 47
I have this function in Ruby
def translate word
vowels=["a","e","I","O","U"]
i=1.to_i
sentense=word.split(" ").to_a
puts sentense if sentense.length >=1
sentense.split("")
puts sentense
end
I have this phrase "this is a test phrase " and at first I want to create an array that looks like:
["this","is","a", "test", "phrase"]
Then I want to create another array it to look like:
[["t","h","i","s"],["i","s"],["a"],["t","e","s","t"],["p","h","r","a","s","e"]
.
I tried
sentense=word.split(" ").to_a
new_array=sentense.split("").to_a
but it didn't work
Upvotes: 2
Views: 81
Reputation: 110685
def chop_up(str)
str.strip.each_char.with_object([[]]) { |c,a| c == ' ' ? (a << []) : a.last << c }
end
chop_up "fee fi fo fum"
#=> [["f", "e", "e"], ["f", "i"], ["f", "o"], ["f", "u", "m"]]
chop_up " fee fi fo fum "
#=> [["f", "e", "e"], ["f", "i"], ["f", "o"], ["f", "u", "m"]]
chop_up "feefifofum "
#=> [["f", "e", "e", "f", "i", "f", "o", "f", "u", "m"]]
chop_up ""
#=> [[]]
Upvotes: 1
Reputation: 33420
You could use String#split
, Enumerable#map
and String#chars
:
p "this is a test phrase".split.map(&:chars)
# => [["t", "h", "i", "s"], ["i", "s"], ["a"], ["t", "e", "s", "t"], ["p", "h", "r", "a", "s", "e"]]
string.split(' ')
could be written as string.split
, so you can omit passing the whitespace in parenthesis.
And this also gives you an array, there's no need to use to_a
, you'll have an array like ["this", "is", "a", "test", "phrase"]
, so you can use map to get a new array and for each element inside an array of its characters by using .split('')
or .chars
.
Upvotes: 6