Help solving a problem

Hello all,

I am reading the book Ruby on Rails Tutorial : Learning by Example

At the end of chapter 4 theres a question. I tried many time but nit
succeeding in solving it.

Can you all please help me in writing a solution for the same?

Question is :

Using Listing 4.9 as a guide, combine the split, shuffle, and join
methods to write a function that shuffles the letters in a given

Listing 4.9. Skeleton for a string shuffle function :

def string_shuffle(s)
=> nil


Thank you

On Sun, Nov 13, 2011 at 6:01 PM, Praveer [email protected]


Hi, to tackle such a question, I would use a combination of:

  • irb (or pry)
  • ruby documentation (e.g.
  • use the .class and .inspect method intensively to study what type and
    the result of each intermediate step is

So, in the session below, you see how I would build-up the result of

[email protected]:~$ ruby -v
ruby 1.9.3p0 (2011-10-30 revision 33570) [i686-linux]
[email protected]:~$ irb
001:0> s = “foobar”
=> “foobar”
002:0> s.class
=> String
003:0> s.inspect
=> ““foobar””
004:0> # now look up the documentation for String#split (
005:0* ^C
005:0> s_split = s.split(’’)
=> [“f”, “o”, “o”, “b”, “a”, “r”]
006:0> # now look up the documentation for Array#shuffle
007:0* ^C
007:0> s_split_shuffle = s_split.shuffle
=> [“o”, “o”, “f”, “r”, “a”, “b”]
008:0> s_split_shuffle.class
=> Array
009:0> # now look up the documentation for Array#join
010:0* ^C
010:0> result = s_split_shuffle.join
=> “oofrab”
011:0> result.class
=> String
012:0> # so the answer is s.split(’’).shuffle.join
013:0* ^C


010:0* ^C
010:0> result = s_split_shuffle.join
=> “oofrab”
011:0> result.c

Thanks a lot mate. I was doing maximum right, but the way I was
usaging the split and shuffle was wrong.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs