在字符串中交替大小写单词的更简单方法
Simpler way to alternate upper and lower case words in a string
我最近解决了这个问题,但觉得有更简单的方法。我查看了 inject、step 和 map,但无法弄清楚如何将它们实现到这段代码中。我想使用比现在更少的代码行。我是 ruby 的新手,所以如果答案很简单,我很乐意将其添加到我的工具包中。提前谢谢你。
目标:接受一个句子字符串作为arg,return单词大小写交替的句子
def alternating_case(str)
newstr = []
words = str.split
words.each.with_index do |word, i|
if i.even?
newstr << word.upcase
else
newstr << word.downcase
end
end
newstr.join(" ")
end
您可以使用三元条件 (true/false ? value_if_true : value_if_false):
来减少 each_with_index 块中的行数
words.each.with_index do |word, i|
newstr << i.even? ? word.upcase : word.downcase
end
至于完全不同的方法,您可以逐个字母地遍历初始字符串,然后在您点击 space:
时更改方法
def alternating_case(str)
@downcase = true
new_str = str.map { |letter| set_case(letter)}
end
def set_case(letter)
@downcase != @downcase if letter == ' '
return @downcase ? letter.downcase : letter.upcase
end
我们可以使用 ruby 的 Array#cycle
来实现。
Array#cycle
returns 一个 Enumerator
对象,如果给定 none 或 nil,它会为枚举的每个元素重复调用 n 次或永远调用块。
cycle_enum = [:upcase, :downcase].cycle
#=> #<Enumerator: [:upcase, :downcase]:cycle>
5.times.map { cycle_enum.next }
#=> [:upcase, :downcase, :upcase, :downcase, :upcase]
现在,使用上面的我们可以写成如下:
word = "dummyword"
cycle_enum = [:upcase, :downcase].cycle
word.chars.map { |c| c.public_send(cycle_enum.next) }.join("")
#=> "DuMmYwOrD"
注意:如果您是 ruby 的新手,您可能不熟悉 public_send
或 Enumberable
模块。您可以使用以下参考资料。
我最近解决了这个问题,但觉得有更简单的方法。我查看了 inject、step 和 map,但无法弄清楚如何将它们实现到这段代码中。我想使用比现在更少的代码行。我是 ruby 的新手,所以如果答案很简单,我很乐意将其添加到我的工具包中。提前谢谢你。
目标:接受一个句子字符串作为arg,return单词大小写交替的句子
def alternating_case(str)
newstr = []
words = str.split
words.each.with_index do |word, i|
if i.even?
newstr << word.upcase
else
newstr << word.downcase
end
end
newstr.join(" ")
end
您可以使用三元条件 (true/false ? value_if_true : value_if_false):
来减少 each_with_index 块中的行数words.each.with_index do |word, i|
newstr << i.even? ? word.upcase : word.downcase
end
至于完全不同的方法,您可以逐个字母地遍历初始字符串,然后在您点击 space:
时更改方法def alternating_case(str)
@downcase = true
new_str = str.map { |letter| set_case(letter)}
end
def set_case(letter)
@downcase != @downcase if letter == ' '
return @downcase ? letter.downcase : letter.upcase
end
我们可以使用 ruby 的 Array#cycle
来实现。
Array#cycle
returns 一个 Enumerator
对象,如果给定 none 或 nil,它会为枚举的每个元素重复调用 n 次或永远调用块。
cycle_enum = [:upcase, :downcase].cycle
#=> #<Enumerator: [:upcase, :downcase]:cycle>
5.times.map { cycle_enum.next }
#=> [:upcase, :downcase, :upcase, :downcase, :upcase]
现在,使用上面的我们可以写成如下:
word = "dummyword"
cycle_enum = [:upcase, :downcase].cycle
word.chars.map { |c| c.public_send(cycle_enum.next) }.join("")
#=> "DuMmYwOrD"
注意:如果您是 ruby 的新手,您可能不熟悉 public_send
或 Enumberable
模块。您可以使用以下参考资料。