I see what you expect this. It is a scope problem.
The variable hash
already exists both inside and outside of the block as a function call. Whenever you declare a variable or function with the same name you will be shadowing it in that scope - that is, make the older invalid and using your just defined behaviour for that name.
In your case, you declared it in the scope of your block, and so shadowed the Object#hash
function as a string variable inside the do/end
block. However, the variable was not shadowed outside of your block, and thus kept the original function call.
So, for example
hash = ''
define_method :hash_count do
hash << 'X' while hash.length < 25
hash # returns the hash from the method
end
puts hash
Should work as you expected because you are shadowing the hash in the same scope your are using puts. For similar reasons, if you do
def hash_count
a = ''
a << 'X' while hash.length < 25
a # returns the hash from the method
end
puts a
it should raise an undefined variable error, because it is not defined in this scope.