Home>

Thanks for your attention.
I was practicing how to write each and for today, and can you tell me why you didn't understand the response to the program?
for i in 15..20 do
puts"# {i} hello"
end

for i in ["desk","chair"]
p i
end

for name, id in {taniguchi: 177322, murata: 177332}
p"# {name}, # {id}"
end

(15..20) .each do | i |
p i
end

["red","blue"]. each do | i |
p i
end

{taguchi: 322, murata: 177332} .each do"| i | # {name}, # {id}"
p i
end
I wrote a program called
{taguchi: 322, murata: 177332} .each do"| i | # {name}, # {id}"
p i
end
Reply
"chair"
"chair"
have become.
Ideally,
"taguchi, 322"
"murata, 177332"
It was scheduled to be.
By the way, the program that goes as planned is to be applied.
However, I was not satisfied with this result that came out on the way, so I would like to know why.

  • Answer # 1

    The valid range of block parameters such as

    each(variables enclosed in|) is limited to blocks, butforvariables are It is valid after the block ends.
    That is,

    for i in ["desk", "chair"]
    p i
    end


    Theivalue at the end of the execution is"chair", which remains in effect.
    Then

    (15..20) .each do | i |
    p i
    end


    Butihas appeared, but thisiis a block parameter and is not related to the outeri.

    {taguchi: 322, murata: 177332} .each do "| i | # {name}, # {id}"
    p i
    end


    Soiis not declared as a block parameter, sopihas an outerior"chair"is referenced.

    "| i | # {name}, # {id}"is just a string. Fornameandid, the value assigned by the previousfor name, idremains, and as a whole," ;| i | murata, 177332".