Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion lib/csv/row.rb
Original file line number Diff line number Diff line change
Expand Up @@ -637,6 +637,7 @@ def ==(other)

# :call-seq:
# row.to_h -> hash
# row.to_h {|key, value| ... } -> hash
#
# Returns the new \Hash formed by adding each header-value pair in +self+
# as a key-value pair in the \Hash.
Expand All @@ -650,10 +651,21 @@ def ==(other)
# table = CSV.parse(source, headers: true)
# row = table[0]
# row.to_h # => {"Name"=>"Foo"}
#
# If a block is given, will call it with (key, value) arguments and use result as a hash entry:
# source = "Name,Value\nfoo,1\nbar,2\nbaz,3\n"
# table = CSV.parse(source, headers: true)
# row = table[0]
# row.to_h { |key, value| [key, value.to_i * 2] } # => {"Name"=>"foo", "Value"=>2}
def to_h
hash = {}
each do |key, _value|
hash[key] = self[key] unless hash.key?(key)
next if hash.key?(key)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

key may be changed by yield(key, value). So we can't do this if block_given?.

How about using separated each?

if block_given?
  each do |key, _value|
    key, value = yield(key, self[key])
    hash[key] = value unless hash.key?(key)
  end
else
  each do |key, _value|
    hash[key] = self[key] unless hash.key?(key)
  end
end


value = self[key]
key, value = yield(key, value) if block_given?
Comment on lines 662 to +666
Comment on lines 660 to +666

hash[key] = value
Comment on lines 662 to +668
end
hash
end
Expand Down
6 changes: 6 additions & 0 deletions test/csv/test_row.rb
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,12 @@ def test_to_hash
end
end

def test_to_hash_with_block
row = CSV::Row.new(%w{A A B C}, [1, 2, 2, 3])
hash = row.to_hash { |k, v| [k, v**2] }
assert_equal({"A" => 1, "B" => 4, "C" => 9}, hash)
Comment on lines +345 to +347
end

def test_to_csv
# normal conversion
assert_equal("1,2,3,4,\n", @row.to_csv)
Expand Down
Loading