summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorjeg2 <jeg2@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2012-12-27 16:15:53 +0000
committerjeg2 <jeg2@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2012-12-27 16:15:53 +0000
commit93030d0e4d93683346648b25bd69a3f33a5f0486 (patch)
treeafffbf80d989e519a5b2f7131c46304de4d7d61b /lib
parent7b34c2f81aa300aa943479077c7c19c472b0c71c (diff)
* lib/csv.rb: Added more Hash methods to CSV::Row.
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@38633 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'lib')
-rw-r--r--lib/csv.rb38
1 files changed, 37 insertions, 1 deletions
diff --git a/lib/csv.rb b/lib/csv.rb
index a0209223c2..279890e7e0 100644
--- a/lib/csv.rb
+++ b/lib/csv.rb
@@ -274,7 +274,7 @@ class CSV
# field( header, offset )
# field( index )
#
- # This method will fetch the field value by +header+ or +index+. If a field
+ # This method will return the field value by +header+ or +index+. If a field
# is not found, +nil+ is returned.
#
# When provided, +offset+ ensures that a header match occurrs on or later
@@ -293,6 +293,42 @@ class CSV
#
# :call-seq:
+ # fetch( header )
+ # fetch( header ) { |row| ... }
+ # fetch( header, default )
+ #
+ # This method will fetch the field value by +header+. It has the same
+ # behavior as Hash#fetch: if there is a field with the given +header+, its
+ # value is returned. Otherwise, if a block is given, it is yielded the
+ # +header+ and its result is returned; if a +default+ is given as the
+ # second argument, it is returned; otherwise a KeyError is raised.
+ #
+ def fetch(header, *varargs)
+ raise ArgumentError, "Too many arguments" if varargs.length > 1
+ pair = @row.assoc(header)
+ if pair
+ pair.last
+ else
+ if block_given?
+ yield header
+ elsif varargs.empty?
+ raise KeyError, "key not found: #{header}"
+ else
+ varargs.first
+ end
+ end
+ end
+
+ # Returns +true+ if there is a field with the given +header+.
+ def has_key?(header)
+ !!@row.assoc(header)
+ end
+ alias_method :include?, :has_key?
+ alias_method :key?, :has_key?
+ alias_method :member?, :has_key?
+
+ #
+ # :call-seq:
# []=( header, value )
# []=( header, offset, value )
# []=( index, value )