【问题标题】:Ruby Array Index - Every other word upcaseRuby 数组索引 - 每隔一个单词大写
【发布时间】:2016-07-22 14:35:39
【问题描述】:
wordSort.sort!

=begin
Conditional is performed on the array: if array index is equal to zero or has 
a remainder of zero after being divided by 2 then call upcase method on element.
Else call lowercase method on that index number.
=end

puts ""

puts "Here are the words you entered:"

puts wordSort

【问题讨论】:

  • 您要返回字符串还是数组?如果是字符串,则您对问题的描述包含隐含假设,即必须将字符串转换为单词数组,更改大小写,然后将数组的元素连接回字符串。直接对字符串进行操作更有意义。如果您希望返回一个数组,可以在更改大小写之前或之后将字符串拆分为一个数组或单词。
  • 家庭作业问题,没有任何尝试的证据。
  • Ruby 的一个约定是对变量和方法的名称使用“蛇形大小写”。此类名称应以小写字母开头,后跟小写字母、数字和下划线。例如,您应该写 word_sort 而不是 wordSort。您不必接受约定,但 99% 以上的 Rubies 都可以。
  • 如果您发现任何答案有帮助,请考虑选择(即✅)您最喜欢的答案。 (是的,我知道只有一个答案。)

标签: arrays ruby indexing upcase


【解决方案1】:
enum = [:upcase, :downcase].cycle
  #=> #<Enumerator: [:upcase, :downcase]:cycle> 
"Here are the words you entered:".gsub(/\w+/) { |x| x.send enum.next }
  #=> "HERE are THE words YOU entered:"

【讨论】:

  • 感谢您的回复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-22
  • 2012-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多