0

My code is:

def LetterChanges(str)
  str.each_char {|x| print x.next!}
end

LetterChanges("hello")

Which returns:

 "ifmmp" => "hello"

How do I get it to only return "ifmmp"? Any help would be greatly appreciated.

4

4 回答 4

5
"hello".gsub(/./, &:next)
# => "ifmmp"
于 2013-08-02T20:18:29.980 回答
2
def LetterChanges(str)
 str.chars.map(&:next).join("")
end

LetterChanges("hello")
# => "ifmmp"

or

def LetterChanges(str)
 str.size.times{|i| str[i] = str[i].next }
 str
end

LetterChanges("hello")
# => "ifmmp"
于 2013-08-02T20:14:38.533 回答
0
puts str;

This should do it for you.

于 2013-08-02T20:14:11.787 回答
0

The solution is easy:

def LetterChanges(str)
    puts str.chars.map(&:next).join
end

but I'd suggest you to refactor it to let puts out. This way you don't hardcode the print of the value and you just make it return the string so that the user of the method can do whatever he wants with that value:

def LetterChanges(str)
    str.chars.map(&:next).join
end

and then you can just do:

puts LetterChanges("hello")
# => "ifmmp"
于 2013-08-02T20:20:39.197 回答