Strange values being output to screen from ruby script -


define_method :hash_count    hash = ''   hash << 'x' while hash.length < 25   hash # returns hash method end  puts hash 

i expecting

xxxxxxxxxxxxxxxxxxxxxxxx 

to outputted screen. instead bizarre random numbers such

3280471151433993928 

and

-1945829393073068570 

could please explain? scoping in ruby seems way weirder in php/javascript!

i see expect this. scope problem.

the variable hash exists both inside , outside of block function call. whenever declare variable or function same name shadowing in scope - is, make older invalid , using defined behaviour name.

in case, declared in scope of block, , shadowed object#hash function string variable inside do/end block. however, variable not shadowed outside of block, , kept original function call.

so, example

hash = '' define_method :hash_count    hash << 'x' while hash.length < 25   hash # returns hash method end  puts hash 

should work expected because shadowing hash in same scope using puts. similar reasons, if do

def hash_count   = ''   << 'x' while hash.length < 25   # returns hash method end  puts 

it should raise undefined variable error, because not defined in scope.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -