mirror of
https://github.com/ruby/ruby.git
synced 2022-11-09 12:17:21 -05:00
* lib/ostruct.rb (each_pair): Add #each_pair [#1400]
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@37372 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
parent
2dafb0f47a
commit
15d4862b91
3 changed files with 22 additions and 0 deletions
1
NEWS
1
NEWS
|
@ -118,6 +118,7 @@ with all sufficient information, see the ChangeLog file.
|
|||
|
||||
* ostruct
|
||||
* new methods:
|
||||
* OpenStruct#each_pair
|
||||
* OpenStruct#to_h converts the struct to a hash.
|
||||
|
||||
* pathname
|
||||
|
|
|
@ -113,6 +113,20 @@ class OpenStruct
|
|||
@table.dup
|
||||
end
|
||||
|
||||
#
|
||||
# Yields all attributes (as a symbol) along with the corresponding values
|
||||
# or returns an enumerator if not block is given.
|
||||
# Example:
|
||||
#
|
||||
# require 'ostruct'
|
||||
# data = OpenStruct.new("country" => "Australia", :population => 20_000_000)
|
||||
# data.each_pair.to_a # => [[:country, "Australia"], [:population, 20000000]]
|
||||
#
|
||||
def each_pair
|
||||
return to_enum __method__ unless block_given?
|
||||
@table.each_pair{|p| yield p}
|
||||
end
|
||||
|
||||
#
|
||||
# Provides marshalling support for use by the Marshal library.
|
||||
#
|
||||
|
|
|
@ -85,4 +85,11 @@ class TC_OpenStruct < Test::Unit::TestCase
|
|||
|
||||
assert_equal(h, OpenStruct.new("name" => "John Smith", "age" => 70, pension: 300).to_h)
|
||||
end
|
||||
|
||||
def test_each_pair
|
||||
h = {name: "John Smith", age: 70, pension: 300}
|
||||
os = OpenStruct.new(h)
|
||||
assert_equal '#<Enumerator: #<OpenStruct name="John Smith", age=70, pension=300>:each_pair>', os.each_pair.inspect
|
||||
assert_equal [[:name, "John Smith"], [:age, 70], [:pension, 300]], os.each_pair.to_a
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Add table
Reference in a new issue