-1

Without changing any of the other code- What can I put into my if else statement to make array 0, 2, 4 show up as all capital letters? I can't figure out how to assign this within the if and else statement.

test = []

puts "Please type 5 different words when you're ready-"

5.times do
  test << gets.chomp
end

test.sort.each do |user|

  if #what could I put in this statement for all capital letters on [0,2,4]?
    user.upcase
  else #.downcase isn't needed, if its simpler to remove it that is fine
    user.downcase
  end
end
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
whatabout11
  • 69
  • 1
  • 7
  • Is there a reason that you can't modify any of the other code? Because the obvious option is `with_index`. – Yu Hao Aug 30 '15 at 03:40
  • there is a method to do it without the with_index, i cant figure it out though. It's the way I have to build it, and the method wasn't made clear to me – whatabout11 Aug 30 '15 at 03:43
  • @whatabout11 there's no other way (short of keeping your own running variable updated within the loop). there's a few answers that clarify and expand on using `each_with_index` at http://stackoverflow.com/questions/533837/automatic-counter-in-ruby-for-each – thomasfuchs Aug 30 '15 at 03:47
  • I think your right @thomasfuchs , been staring at this for awhile – whatabout11 Aug 30 '15 at 03:51

2 Answers2

1

I think what you need to do is change the each loop to each_with_index. The each_with_index loop should get what you need.

test.sort.each_with_index do |user, index|
  if ([0,2,4]include? index)
    user.upcase
  else
    user.downcase
  end
end

If the array is going to expand, you could use the #even? method on the index as the check in the if statement like so.

test.sort.each_with_index do |user, index|
  if (index.even?)
    user.upcase
  else
    user.downcase
  end
end

If you can't change the type of loop then you could use the #index method on the array, to tell you where the user is in the test array like so

test.sort.each do |user|
  if ([0,2,4].include? (test.sort.index(user)))
    user.upcase
  else
    user.downcase
  end
end
0

Why without changing any of the other code? Just do this, no one will care:

puts "Please type 5 different words when you're ready-"
5.times.map { |i| i.even? ? gets.chomp.downcase : gets.chomp.upcase }

The times loop autoindexes for this reason, and the ternary operator (?:) is built for this case.

fdisk
  • 418
  • 2
  • 8