user3384982
user3384982

Reputation: 1

Ruby loops random outputs

So i'm writing a simple program that generates 20 sentences based on randomly selecting a verb, noun, preposition, and article from separate arrays. Basically i have 4 separate arrays with 5 words each pertaining to a respective part of speech.

I have a loop set to run 20 times, which displays a sentence containing a word or two at random from each array. The problem I currently have is that the program is simply generating 20 instances of the same sentence, rather than 20 different random sentences. My loop statement currently looks like this:

20.times do
puts article[randarticle].capitalize + "\s" + noun[randnoun] + "\s" + verb[randverb
] + "\s" + prep[randprep] + "\s" + article[randarticle2] + "\s" + noun[randnoun2] 
+ "."
end

I know this is not the correct syntax for what i want, but i cannot seem to figure it out. Any and all help would be appreciated!!

Upvotes: 0

Views: 456

Answers (1)

BroiSatse
BroiSatse

Reputation: 44685

Assuming you have all articles, verbs etc. in arrays it is as simple as:

20.times do
  puts [articles, nouns, verbs, preps, articles, nouns].map(&:sample).join(' ').capitalize + '.' 
end

Upvotes: 1

Related Questions