Railstutorial (Michael Hartl): Exercise 4.6

I do not get the answer to the following exercise from the Hartl Rails tutorial:

Replacing the question marks in Listing 4.10 with the appropriate methods, combine split, shuffle, and join to write a function that shuffles the letters in the given string.

Listing 4.10:

>> def string_shuffle(s) >> s.split('').?.? >> end => nil >> string_shuffle("foobar") 

Can anyone help me out?

Thank you very much!

+4
source share
1 answer

I think just adding shuffle and join, as you said, should work:

 def string_shuffle(s) s.split('').shuffle.join('') end 

Methods work from left to right. Separation ('') splits a word into an array of individual letters. Shuffle then randomizes them. And join ('') cancels the split and returns it in one word.

edit for clarification: ('') is two single quotes, not one double quote. It should also work if you split (") and join (" "), since you're just trying to split and join each character.

+6
source

Source: https://habr.com/ru/post/1441429/


All Articles