我的代碼是:如何在使用each_char時刪除原始字符串?
def LetterChanges(str)
str.each_char {|x| print x.next!}
end
LetterChanges("hello")
將返回:
"ifmmp" => "hello"
我如何讓它只返回"ifmmp"
?任何幫助將不勝感激。
我的代碼是:如何在使用each_char時刪除原始字符串?
def LetterChanges(str)
str.each_char {|x| print x.next!}
end
LetterChanges("hello")
將返回:
"ifmmp" => "hello"
我如何讓它只返回"ifmmp"
?任何幫助將不勝感激。
puts str;
這應該爲你做。
這需要更多的解釋和上下文。 –
def LetterChanges(str)
str.chars.map(&:next).join("")
end
LetterChanges("hello")
# => "ifmmp"
或
def LetterChanges(str)
str.size.times{|i| str[i] = str[i].next }
str
end
LetterChanges("hello")
# => "ifmmp"
解決辦法很簡單:
def LetterChanges(str)
puts str.chars.map(&:next).join
end
,但我建議你重構它讓puts
出來。這樣,你不硬編碼值的打印,你只要讓它返回字符串,這樣的方法,用戶可以做任何他想做的與值:
def LetterChanges(str)
str.chars.map(&:next).join
end
,然後你可以這樣做:
puts LetterChanges("hello")
# => "ifmmp"
您應該獎勵一個選定的答案,無論哪個人是正確的和/或幫助你解決你的問題。 –