0

Say I'm having two strings "Cat" and "Mouse"

I put them in an array

arr = ["Cat","Mouse"]

And I have two variables say hero and villain

Now the variable hero will be assigned dynamically which will be either "Cat" or "Mouse"

So what will be the best way to assign villain variable by eliminating hero value from arr

Ex

hero = # Either "Cat" or "Mouse"
villain = # The NOT HERO VALUE in arr

FYI: I know it can be done using a function or some manual tricks. But I just wonder if there is any Ruby way of doing this.

4

3 回答 3

3
arr = ["Cat","Mouse"]
arr.shuffle!

hero = arr.pop
villain = arr.pop

Or, you can simple write:

hero, villain = arr.shuffle!

(no splat(*) needed)

于 2013-07-24T05:42:26.287 回答
2

You can do

villain = (arr - [hero])[0]

This works well if you already know who your hero is. If you want to pick both randomly at the same time, 7stud's is better. Or this nondestructive variant:

hero, villain = *arr.shuffle
于 2013-07-24T05:43:01.717 回答
1

Just to cover sample method:

arr = ["Cat","Mouse"]
hero, villain = arr.sample(2)
于 2013-07-24T06:02:33.067 回答