In the following program (written in irb shell) i call a method hidden of the class Tester that accepts 2 arguments both of them string and then returns a string after modifying them. I get an output which i don’t expect.
What i expect is:
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
ACTUAL CODE:
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"
Why is that ? Is it a different matter in Ruby as compared to some other OOP language like Java ?
The Problem
You don’t have the string you think you do. Forget the method, just do it line-by-line:
This is all exactly as it should be.
The Solution
If you want “suhailatpugliahus” then you need to avoid reassigning a new value to anotherStr.