summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--NEWS1
-rw-r--r--lib/ostruct.rb14
-rw-r--r--test/ostruct/test_ostruct.rb7
3 files changed, 22 insertions, 0 deletions
diff --git a/NEWS b/NEWS
index 967196dcd8..f76f676728 100644
--- a/NEWS
+++ b/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
diff --git a/lib/ostruct.rb b/lib/ostruct.rb
index 894abce89f..e22fca3e46 100644
--- a/lib/ostruct.rb
+++ b/lib/ostruct.rb
@@ -114,6 +114,20 @@ class OpenStruct
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.
#
def marshal_dump
diff --git a/test/ostruct/test_ostruct.rb b/test/ostruct/test_ostruct.rb
index 1826e40e53..9b125fc055 100644
--- a/test/ostruct/test_ostruct.rb
+++ b/test/ostruct/test_ostruct.rb
@@ -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