我是Ruby新手,我需要您提供以下帮助:
任务是编写一个将返回以下结果的函数:
"Hello", "hEllo", "heLlo", "helLo", "hellO"
还需要处理“两个词”
我遇到的问题是字母'L',因为该函数似乎在字符串中将它们都大写。
这是我的代码:
def wave(str)
str.each do |word|
count = -1
word.length.times do
count += 1
puts word.gsub(word[count],word[count].capitalize)
end
end
end
wave("hello")
答案 0 :(得分:2)
这应该有效:
str = 'hi fi'
p str.size.times.map{ str.dup }.map.with_index{ |s, i| s[i] = s[i].upcase; s unless s[i] == ' '}.compact
#=> ["Hi fi", "hI fi", "hi Fi", "hi fI"]
这是它的工作方式:
首先构建一个数组,该数组包含单词的n倍,其中n是单词长度:
str.size.times.map{ str.dup } #=> ["hello", "hello", "hello", "hello", "hello"]
请注意,.dup
是必需的,以便能够在不影响所有元素的情况下修改数组的每个元素。
然后,用索引(Enummerator#with_index)映射以大写索引处的字母。最终返回s
除非当前字符是空格,否则返回nil
,这就是调用.compact
的原因。
这是修改后的OP方法,无需传递字符串数组作为参数:
def wave(str)
str.length.times do |n|
str_dup = str.dup
str_dup[n] = str_dup[n].capitalize
puts str_dup unless str_dup[n] == ' '
end
end
wave('hi fi')
#=> Hi fi
#=> hI fi
#=> hi Fi
#=> hi fI
答案 1 :(得分:2)
def rep_it(word)
Array.new(word.size) {|i| word [0,i] << word[i].upcase << word[i+1..-1].to_s}
end
rep_it 'hello'
#=> ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
Array::new在这里效果很好,因为所需的字符索引已内置在方法中。
当i == word.size-1
时,<< word[word.size]
(<< nil
)将引发异常;因此(诀窍)<< nil.to_s
(<< ''
)。 (请参见NilClass#to_s。)更长,但可以说更清楚的是,将代码块编写如下:
{|i| word [0,i] << word[i].upcase << ((i < word.size-1) ? word[i+1..-1] : '')}
答案 2 :(得分:0)
这是我想出的解决方案
s = "hello there"
s.each_char.with_index.with_object([]) do |(l,i),arr|
arr << "#{s}" and arr.last[i] = l if l.upcase!
end
#=> ["Hello there",
# "hEllo there",
# "heLlo there",
# "helLo there",
# "hellO there",
# "hello There",
# "hello tHere",
# "hello thEre",
# "hello theRe",
# "hello therE"]
如果某个字符可以大写(例如/[a-z]/
)if l.upcase!
,则将str的副本推入Array
(arr << "#{s}"
)中,然后将字符替换为{{ 1}},现在使用大写版本(str[i]
)