【问题标题】:How should I setup this if and else statement? [duplicate]我应该如何设置这个 if 和 else 语句? [复制]
【发布时间】:2015-08-30 03:34:07
【问题描述】:

在不更改任何其他代码的情况下- 我可以在我的 if else 语句中添加什么以使数组 0、2、4 显示为全大写字母?我不知道如何在 if 和 else 语句中分配它。

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

【问题讨论】:

  • 是否有不能修改其他代码的原因?因为显而易见的选项是with_index
  • 有一种方法可以在没有 with_index 的情况下执行此操作,但我无法弄清楚。这是我必须构建它的方式,我并不清楚该方法
  • @whatabout11 没有其他办法(除了在循环中更新您自己的运行变量)。在stackoverflow.com/questions/533837/…each_with_index 上使用each_with_index 有一些答案可以澄清和扩展
  • 我认为你的权利@thomasfuchs 已经盯着这个看了一段时间

标签: ruby


【解决方案1】:

我认为您需要做的是将each 循环更改为each_with_indexeach_with_index 循环应该可以满足您的需要。

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

如果数组要扩展,您可以使用index 上的#even? 方法作为 if 语句中的检查,如下所示。

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

如果您无法更改循环的类型,那么您可以使用数组上的#index 方法,告诉您usertest 数组中的位置,就像这样

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

【讨论】:

    【解决方案2】:

    为什么不更改任何其他代码?就这样做,没人会在意:

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

    times 循环出于这个原因自动索引,并且为此情况构建了三元运算符 (?:)。

    【讨论】:

      猜你喜欢
      • 2015-10-19
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 2022-08-10
      相关资源
      最近更新 更多