Randomly Sorting Strings

W

woodyee

Hi! I'm trying to write a program that will print out a different
string each time it's run from a list of strings.

For example:

example = ['one', 'two', 'three']
# sort them somehow
# 'two' prints out as the output, for example
# run it again and a different string prints out

Make sense? I've tried srand & rand but can't do this with strings. Do
I need to forget the arrays and try something else? I've looked at the
Pickaxe book and Ruby Cookbook but can't find anything. Thanks!
 
S

Sharon Phillips

try

example= %w[one two three cat dog cow table]
puts example[rand(example.size)]

Cheers,
Dave
 
S

Stefan Rusterholz

Sharon said:
try

example= %w[one two three cat dog cow table]
puts example[rand(example.size)]

Cheers,
Dave

Another example would be:

example= %w[one two three cat dog cow table].sort_by { rand }
example.each { |string|
puts string
}

that will print all in random order

my regards
 
S

Stefan Rusterholz

Robert said:
this is a Ruby Quiz Spoiler!!!
Robert

I apologize. I didn't read the current quiz.
Does that mean I have to check back with the current quiz when somebody
asks for help in here?

my regards
 
D

dblack

Hi --

Sharon said:
try

example= %w[one two three cat dog cow table]
puts example[rand(example.size)]

Cheers,
Dave

Another example would be:

example= %w[one two three cat dog cow table].sort_by { rand }
example.each { |string|
puts string
}

You can replace the last three lines with:

puts example

:)


David

--
Q. What is THE Ruby book for Rails developers?
A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black)
(See what readers are saying! http://www.rubypal.com/r4rrevs.pdf)
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)
 
J

James Edward Gray II

I personally chose to try to avoid to post any material too much
related to
the Quiz and furthermore I point it out to others who might not be
interested in the Quiz.

Overlap happens. No big deal. It just means I chose well for the
quiz topic and it will be helpful in the future. ;)

James Edward Gray II
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top