List comprehension in Ruby

2019-01-10 04:57发布

To do the equivalent of Python list comprehensions, I'm doing the following:

some_array.select{|x| x % 2 == 0 }.collect{|x| x * 3}

Is there a better way to do this...perhaps with one method call?

14条回答
Evening l夕情丶
2楼-- · 2019-01-10 05:41

I made a quick benchmark comparing the three alternatives and map-compact really seems to be the best option.

Performance test (Rails)

require 'test_helper'
require 'performance_test_help'

class ListComprehensionTest < ActionController::PerformanceTest

  TEST_ARRAY = (1..100).to_a

  def test_map_compact
    1000.times do
      TEST_ARRAY.map{|x| x % 2 == 0 ? x * 3 : nil}.compact
    end
  end

  def test_select_map
    1000.times do
      TEST_ARRAY.select{|x| x % 2 == 0 }.map{|x| x * 3}
    end
  end

  def test_inject
    1000.times do
      TEST_ARRAY.inject([]) {|all, x| all << x*3 if x % 2 == 0; all }
    end
  end

end

Results

/usr/bin/ruby1.8 -I"lib:test" "/usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/rake_test_loader.rb" "test/performance/list_comprehension_test.rb" -- --benchmark
Loaded suite /usr/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/rake_test_loader
Started
ListComprehensionTest#test_inject (1230 ms warmup)
           wall_time: 1221 ms
              memory: 0.00 KB
             objects: 0
             gc_runs: 0
             gc_time: 0 ms
.ListComprehensionTest#test_map_compact (860 ms warmup)
           wall_time: 855 ms
              memory: 0.00 KB
             objects: 0
             gc_runs: 0
             gc_time: 0 ms
.ListComprehensionTest#test_select_map (961 ms warmup)
           wall_time: 955 ms
              memory: 0.00 KB
             objects: 0
             gc_runs: 0
             gc_time: 0 ms
.
Finished in 66.683039 seconds.

15 tests, 0 assertions, 0 failures, 0 errors
查看更多
一夜七次
3楼-- · 2019-01-10 05:43

Another solution but perhaps not the best one

some_array.flat_map {|x| x % 2 == 0 ? [x * 3] : [] }

or

some_array.each_with_object([]) {|x, list| x % 2 == 0 ? list.push(x * 3) : nil }
查看更多
不美不萌又怎样
4楼-- · 2019-01-10 05:45

An alternative solution that will work in every implementation and run in O(n) instead of O(2n) time is:

some_array.inject([]){|res,x| x % 2 == 0 ? res << 3*x : res}
查看更多
家丑人穷心不美
5楼-- · 2019-01-10 05:47

I think the most list comprehension-esque would be the following:

some_array.select{ |x| x * 3 if x % 2 == 0 }

Since Ruby allows us to place the conditional after the expression, we get syntax similar to the Python version of the list comprehension. Also, since the select method does not include anything that equates to false, all nil values are removed from the resultant list and no call to compact is necessary as would be the case if we had used map or collect instead.

查看更多
淡お忘
6楼-- · 2019-01-10 05:48

This is more concise:

[1,2,3,4,5,6].select(&:even?).map{|x| x*3}
查看更多
看我几分像从前
7楼-- · 2019-01-10 05:48

Like Pedro mentioned, you can fuse together the chained calls to Enumerable#select and Enumerable#map, avoiding a traversal over the selected elements. This is true because Enumerable#select is a specialization of fold or inject. I posted a hasty introduction to the topic at the Ruby subreddit.

Manually fusing Array transformations can be tedious, so maybe someone could play with Robert Gamble's comprehend implementation to make this select/map pattern prettier.

查看更多
登录 后发表回答