DEV Community

Thomas Dhinsa
Thomas Dhinsa

Posted on

Shuffling Arrays in ruby

Hey all,

I’m going over a problem while learning ruby and would appreciate any help. I’ve been reading everything trying to grasp this. In order to randomize the contents of an array, you have to use the .shuffle method? And if so, why does ruby claim it is an undefined method? Also, how would I get a user input from a gets.chomp to be part of an array? I tried putting it directly into the array, I tried setting it equal to a variable and then tried putting the variable into an array but it kept crashing. I feel like this may be simpler than I am making it. None of the material on arrays is helping. Everybody is working with preset Arrays and not user inputs.

Top comments (4)

Collapse
 
t_schemi profile image
Thomas Dhinsa • Edited

I got the Second part of my last upload with some help.
Stuck on this now

I need to make the array print only the terms that are less than five

def select_less_than_five(array)
index = 0
new_array = []

while
index < array.length
new_array << array[index] < 5
index = index + 1
end

return new_array

p select_less_than_five([10, 3, 4, 55, 32, 6, 1])

end

Collapse
 
hallison profile image
Hallison Batista

Can you show your code?

Collapse
 
t_schemi profile image
Thomas Dhinsa • Edited

word = []
while true
puts "Please enter a word"
w = gets.chomp
word << w
break
end

p word[0].shuffle!

I'm pretty sure my syntax is messed up.

Collapse
 
khaireddine profile image
Hamdi Khaireddine

array_number = [ 1, 2, 3 ] => array_shuffle = array_number.shuffle
array_number = array_number.shuffle
You can assign result directly to him or to another array