2

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

2
  • "but it didn't work" - of course. You'll need to call split on individual elements. Commented Sep 20, 2017 at 15:06
  • split always returns an array, the to_a is superfluous. Commented Sep 20, 2017 at 15:17

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

6 Comments

You don't mention map in your explanation, although it's the essential part.
Sorry, now yes @Stefan.
I did this way because i the phrase will change but i get an undefined method for split def translate word sentense=word.split sentense.split.map(&:chars) puts split end translate("I have this phrase")
You're using split as a variable, but you haven't defined it @CharalambosPouroutides. And the second split isn't needed if you've initialized sentences as word.split, try def translate word; sentense = word.split; sentense.map(&:chars); end; p translate("I have this phrase").
@CharalambosPouroutides you can omit the temporary variable and simply write word.split.map(&:chars)
|
1
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 ""
  #=> [[]]

1 Comment

I would use @Sebastián's answer, but thought mine might be of interest.

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.