prime number test in Ruby

来源:互联网 发布:淘宝如何上首页 编辑:程序博客网 时间:2024/05/21 17:37

I have an array a = [1,2,3,4,5]. I want to test which of the numbers areprime and wanted to produce the output {1=>false, 2=>true, 3=>true, 4=>false, 5=>true}.

Any one liner will be appreciated.

require 'prime'a = [1,2,3,4,5]Hash[a.zip(a.map(&Prime.method(:prime?)))]# => {1=>false, 2=>true, 3=>true, 4=>false, 5=>true}

I posted this as a comment.

require 'prime'a = (1..5).to_aHash[a.map{ |x| [x, x.prime?] }]=> {1=>false, 2=>true, 3=>true, 4=>false, 5=>true}

0 0
原创粉丝点击