user5937268
user5937268

Reputation:

Alternate between uppercase and downcase

I'm trying to ask the user five times to enter a word, and spat the answers on each line alternating with uppercase and lowercase, without using the each_with_index method. I'm also trying to sort the answers alphabetically. Below is what I have done:

words = []

5.times do
  puts "Please enter a word:"
  words << gets.chomp
end

 words.each do |word|
   if words.even?
     puts words.downcase
   elsif words.odd?
     puts words.upcase
   end
 end

but everything I have tried has failed. How can I have the user input alternate between uppercase and downcase without the each_with_index method?

Upvotes: 0

Views: 113

Answers (4)

Gourav
Gourav

Reputation: 576

Try this

words = []
sorted_words = []

5.times do
  puts "Please enter a word:"
  words << gets.chomp
end

words.sort!.each do |w|
  if words.index(w).even?
    sorted_words << w.downcase
  else
    sorted_words << w.upcase
  end
end
p sorted_words

Upvotes: 0

sawa
sawa

Reputation: 168101

words = Array.new(5){puts "Please enter a word:"; gets.chomp}
words.inject(false){|up, word| puts word.send(up ? :upcase : :downcase); !up}

Upvotes: -1

Ilya
Ilya

Reputation: 13487

words.each_slice(2) {|f,s| puts f.downcase; puts s.upcase if s }

Upvotes: 1

Cary Swoveland
Cary Swoveland

Reputation: 110685

words = %w| how now brown cow |

enum = [:upcase, :downcase].cycle
words.map { |w| w.send enum.next }
  #=> ["HOW", "now", " BROWN", "cow"]

Upvotes: 2

Related Questions