-2

次のプログラム(irbシェルで記述)ではhidden、2つの引数を両方とも文字列として受け入れるクラスのメソッドを呼び出し、Testerそれらを変更した後に文字列を返します。予期しない出力が得られます。

私が期待するのは:

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では別問題ですか?

4

1 に答える 1

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"
于 2012-06-15T06:35:28.520 に答える