0

If I say...

a = [1,2,3]
a.shuffle
puts a

...it gives [1,2,3]. If instead I say...

a=[1,2,3]
a.shuffle!
puts a

...it gives me a new order each time I say puts a. So my question is how do I save the order a shuffled array was put into? If it returns [3,1,2] the first time it should keep this order. Does this make sense?

Here is an example of what I'm talking about. Each time I call b I get a different result.

> a=[1,2,3]
=> [1, 2, 3]
> b=a.shuffl­e!
=> [1, 3, 2]
> b
=> [1, 2, 3]
> b
=> [2, 1, 3]
> b
=> [1, 3, 2]
> b
=> [3, 2, 1]

"b" seems to refer to the function a.shuffle instead of the results of the shuffle itself.

The answer:

The problem occured when using the online interpreter on TryRuby.org. Using the interactive Ruby interpreter on my PC gives the correct result. Thanks to everyone for their help!

Spike Fitsch
  • 687
  • 1
  • 6
  • 12
  • `a = [1,2,3]` `b= a.shuffle puts b` ?? – uday Feb 19 '13 at 20:48
  • What do you mean by saving the order? I think it would help if you gave some surrounding code as how you define and call this code e t c. – Jakob W Feb 19 '13 at 20:53
  • 2
    It does not give you a new order each time you `puts a`; it gives you a new random order each time you run your code, since that causes it to be `shuffle!`d again. – Phrogz Feb 19 '13 at 20:56
  • I mean if it shuffles the array into [3,1,2] then every time a is called after that it should give [3,1,2]. – Spike Fitsch Feb 19 '13 at 20:58

3 Answers3

1

Do you need somethinglike this:

a = [1,2,3]

b = a.shuffle

puts b
uday
  • 7,922
  • 4
  • 28
  • 50
1

The problem occured when using the online interpreter on TryRuby.org. Using the interactive Ruby interpreter on my PC gives the correct result. Thanks to everyone for their help!

Spike Fitsch
  • 687
  • 1
  • 6
  • 12
0

a.shuffle returns a shuffling of a, but does not change a itself, so you'd need to assign the result to a different variable (or to a if that's what you want). You need to call a.shuffle! if you want the method to change a directly.

See Why are exclamation marks used in Ruby methods?

Community
  • 1
  • 1