为什么我没有得到我期望的这种方法的反转字符串?

时间:2012-06-15 06:27:12

标签: ruby string return-value

在以下程序中(用irb shell编写)我调用类hidden的方法Tester,它接受​​2个参数,它们都是字符串,然后返回一个字符串修改后。我得到了一个我不期望的输出。

我的期望是:

def hidden(aStr,anotherStr) # After the call aStr = suhail and anotherStr = gupta
  anotherStr = aStr + " " + anotherStr
  # After the above statement anotherStr = suhail gupta
  return aStr + anotherStr.reverse 
  # After the above statement value returned should be suhailliahusatpug
  # i.e suhail + "reversed string of suhailgupta"
  end

  # But i get suhailatpug liahus

实际代码:

1.9.3p194 :001 > class Tester
1.9.3p194 :002?>   def hidden(aStr,anotherStr)
1.9.3p194 :003?>     anotherStr = aStr + " " + anotherStr
1.9.3p194 :004?>     return aStr + anotherStr.reverse
1.9.3p194 :005?>     end
1.9.3p194 :006?>   end
1.9.3p194 :007 > o = Tester.new
=> #<Tester:0x9458b80> 
1.9.3p194 :008 > str1 = "suhail"
=> "suhail" 
1.9.3p194 :009 > str2 = "gupta"
=> "gupta" 
1.9.3p194 :010 > str3 = o.hidden(str1,str2)
=> "suhailatpug liahus" 

为什么?与 Java 等其他OOP语言相比,它是 Ruby 中的不同内容吗?

1 个答案:

答案 0 :(得分:0)

问题

你没有你认为的字符串。忘记方法,只需逐行进行:

# You passed these as parameters, so they're assigned.
aStr = 'suhail'
anotherStr = 'gupta'

# You re-assign a new string, including a space.
anotherStr = aStr + " " + anotherStr
=> "suhail gupta"

# You are concatenating two different strings.
aStr + anotherStr
=> "suhailsuhail gupta"

# You concatenate two strings, but are reversing only the second string.
aStr + anotherStr.reverse
=> "suhailatpug liahus"

这完全应该是这样。

解决方案

如果您想要“suhailatpugliahus”,那么您需要避免将新值重新分配给 anotherStr

def hidden(aStr,anotherStr)
    aStr + (aStr + anotherStr).reverse
end  
hidden 'suhail', 'gupta'
=> "suhailatpugliahus"