Skip to content

Commit

Permalink
Optimize ActiveRecord::Result#last
Browse files Browse the repository at this point in the history
If you only want the last element of a result set, there's no need to create all
of hash_rows. Also, add a test.
  • Loading branch information
bquorning committed Jun 24, 2016
1 parent af834fb commit 763de2a
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
3 changes: 2 additions & 1 deletion activerecord/lib/active_record/result.rb
Expand Up @@ -81,7 +81,8 @@ def first
end

def last
hash_rows.last
return nil if @rows.empty?
Hash[@columns.zip(@rows.last)]
end

def cast_values(type_overrides = {}) # :nodoc:
Expand Down
5 changes: 5 additions & 0 deletions activerecord/test/cases/result_test.rb
Expand Up @@ -27,6 +27,11 @@ def result
{'col_1' => 'row 1 col 1', 'col_2' => 'row 1 col 2'}, result.first)
end

test "last returns last row as a hash" do
assert_equal(
{'col_1' => 'row 3 col 1', 'col_2' => 'row 3 col 2'}, result.last)
end

test "each with block returns row hashes" do
result.each do |row|
assert_equal ['col_1', 'col_2'], row.keys
Expand Down

0 comments on commit 763de2a

Please sign in to comment.