Project

General

Profile

Actions

Bug #14215

closed

result_with_hash change local variable by hash value.

Added by ota42y (ota ota) over 6 years ago. Updated over 6 years ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 2.5.0rc1 (2017-12-14 trunk 61243) [x86_64-darwin16]
[ruby-core:84390]

Description

When there is a local variable with the same name as the hash key,
ERB#result_with_hash changes the local variable by hash value.

This is sample code.


require "erb"

erb_obj = ERB.new("<%=name%> \"Hello <%=first_name%> <%=last_name%>!\"")

name = 'honoka'
last_name = 'kousaka'

puts erb_obj.result_with_hash(first_name: 'kotori', last_name: 'minami')
puts "Top level name is #{name}, #{last_name}" 

user = {first_name: 'umi', last_name: 'sonoda'}
puts erb_obj.result_with_hash(user)
puts "Top level name is #{name}, #{last_name}"

This code's output is...

honoka "Hello kotori minami!"
Top level name is honoka, minami # (not honoka, kousaka)
honoka "Hello umi sonoda!"
Top level name is honoka, sonoda # (not honoka, kousaka)

I think if changes are made within ERB it will be as intended,
but method argument change local variables is an unexpected behavior for user.
(Hash key and variable are completely different concepts...)

I think that the above code should be as follows output.

honoka "Hello kotori minami!"
Top level name is honoka, kousaka
honoka "Hello umi sonoda!"
Top level name is honoka, kousaka

I write patch it's backup local variable and reset after.

Sorry I don't know how to undefine local valiable so I set nil.
news.each { |key| b.local_variable_set(key, nil) }
But there are side effects... please let me know more good code.


Files

result_with_hash.patch (703 Bytes) result_with_hash.patch ota42y (ota ota), 12/21/2017 10:54 AM
Actions #1

Updated by nobu (Nobuyoshi Nakada) over 6 years ago

  • Status changed from Open to Closed

Applied in changeset trunk|r61411.


erb.rb: shadow by keys

  • lib/erb.rb (ERB#new_toplevel): shadow already defined local
    variables by block local variabes, not to overwrite them.
    [ruby-core:84390] [Bug #14215]
Actions

Also available in: Atom PDF

Like0
Like0