ruby-changes:44930
From: kou <ko1@a...>
Date: Tue, 6 Dec 2016 22:58:00 +0900 (JST)
Subject: [ruby-changes:44930] kou:r57003 (trunk): rexml: REXML::Element#[] accepts String or Symbol as attribute name
kou 2016-12-06 22:57:56 +0900 (Tue, 06 Dec 2016) New Revision: 57003 https://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=revision&revision=57003 Log: rexml: REXML::Element#[] accepts String or Symbol as attribute name Added files: trunk/test/rexml/test_element.rb Modified files: trunk/NEWS trunk/lib/rexml/element.rb Index: lib/rexml/element.rb =================================================================== --- lib/rexml/element.rb (revision 57002) +++ lib/rexml/element.rb (revision 57003) @@ -551,6 +551,30 @@ module REXML https://github.com/ruby/ruby/blob/trunk/lib/rexml/element.rb#L551 # Attributes # ################################################# + # Fetches an attribute value or a child. + # + # If String or Symbol is specified, it's treated as attribute + # name. Attribute value as String or +nil+ is returned. This case + # is shortcut of +attributes[name]+. + # + # If Integer is specified, it's treated as the index of + # child. It returns Nth child. + # + # doc = REXML::Document.new("<a attr='1'><b/><c/></a>") + # doc.root["attr"] # => "1" + # doc.root.attributes["attr"] # => "1" + # doc.root[1] # => <c/> + def [](name_or_index) + case name_or_index + when String + attributes[name_or_index] + when Symbol + attributes[name_or_index.to_s] + else + super + end + end + def attribute( name, namespace=nil ) prefix = nil if namespaces.respond_to? :key Index: NEWS =================================================================== --- NEWS (revision 57002) +++ NEWS (revision 57003) @@ -251,6 +251,12 @@ with all sufficient information, see the https://github.com/ruby/ruby/blob/trunk/NEWS#L251 * Readline.quoting_detection_proc and Readline.quoting_detection_proc= [Feature #12659] +* REXML + + * REXML::Element#[]: If String or Symbol is specified, attribute + value is returned. Otherwise, Nth child is returned. This is + backward compatible change. + * set * New methods: Set#compare_by_identity and Set#compare_by_identity?. Index: test/rexml/test_element.rb =================================================================== --- test/rexml/test_element.rb (revision 0) +++ test/rexml/test_element.rb (revision 57003) @@ -0,0 +1,18 @@ https://github.com/ruby/ruby/blob/trunk/test/rexml/test_element.rb#L1 +# frozen_string_literal: false + +require "test/unit/testcase" +require "rexml/document" + +module REXMLTests + class ElementTester < Test::Unit::TestCase + def test_array_reference_string + doc = REXML::Document.new("<language name='Ruby'/>") + assert_equal("Ruby", doc.root["name"]) + end + + def test_array_reference_symbol + doc = REXML::Document.new("<language name='Ruby'/>") + assert_equal("Ruby", doc.root[:name]) + end + end +end -- ML: ruby-changes@q... Info: http://www.atdot.net/~ko1/quickml/