我建議你按如下方式寫。
class Fact
def initialize (fact)
@fact = fact
end
def fact
@fact[:fact]
end
def is_real?
@fact[:real]
end
def speaker
@fact[:speaker]
end
end
創建一些實例。
facts = [["grass is green", true, "Bob"], ["bears are orange", false, "Sue"],
["cats say 'woof'", false, "Bob"], ["dogs are delightful", true, "Hal"]].
map { |f,t,s| Fact.new(fact: f, real: t, speaker: s) }
#=> [#<Fact:0x007fd363e4bcc0 @fact=
# {:fact=>"grass is green", :real=>true, :speaker=>"Bob"}>,
# #<Fact:0x007fd363e4bc20 @fact=
# {:fact=>"bears are orange", :real=>false, :speaker=>"Sue"}>,
# #<Fact:0x007fd363e4bb80 @fact=
# {:fact=>"cats say 'woof'", :real=>false, :speaker=>"Bob"}>,
# #<Fact:0x007fd363e4bae0 @fact=
# {:fact=>"dogs are delightful", :real=>true, :speaker=>"Sue"}>
# ]
分區facts
到passing_facts
和alternative_facts
。
passing_facts, alternative_facts = facts.partition(&:is_real?)
#=> [[#<Fact:0x007fd363e4bcc0 @fact=
# {:fact=>"grass is green", :real=>true, :speaker=>"Bob"}>,
# #<Fact:0x007fd363e4bae0 @fact=
# {:fact=>"dogs are delightful", :real=>true, :speaker=>"Hal"}>
# ],
# [#<Fact:0x007fd363e4bc20 @fact=
# {:fact=>"bears are orange", :real=>false, :speaker=>"Sue"}>,
# #<Fact:0x007fd363e4bb80 @fact=
# {:fact=>"cats say 'woof'", :real=>false, :speaker=>"Bob"}>
# ]
# ]
passing_facts
#=> [#<Fact:0x007fd363e4bcc0 @fact=
# {:fact=>"grass is green", :real=>true, :speaker=>"Bob"}>,
# #<Fact:0x007fd363e4bae0 @fact=
# {:fact=>"dogs are delightful", :real=>true, :speaker=>"Hal"}>
# ]
alternative_facts
# [#<Fact:0x007fd363e4bc20 @fact=
# {:fact=>"bears are orange", :real=>false, :speaker=>"Sue"}>,
# #<Fact:0x007fd363e4bb80 @fact=
# {:fact=>"cats say 'woof'", :real=>false, :speaker=>"Bob"}>
# ]
編制發言人名單alternative_facts
。
alternative_speakers = alternative_facts.map { |f| f.speaker }
#=> ["Sue", "Bob"]
拒絕的passing_facts
的量,鍵:speaker
的值的alternative_speakers
成員的元素,然後映射那些剩餘的事實的名稱。
passing_facts.reject { |f| alternative_speakers.include?(f.speaker) }.
map { |f| f.fact }
#=> ["dogs are delightful"]
注
passing_facts.reject { |f| alternative_speakers.include?(f.speaker) }
#=> [#<Fact:0x007fd364a38e70 @fact=
# {:fact=>"dogs are delightful", :real=>true, :speaker=>"Hal"}>
# ]
如果有大量的「事實」的,效率可通過加入require 'set'
和粘性.to_set
到計算facts
表達的端部改善。
一個簡單的例子,有預期的結果,會有幫助。 –
你的問題標題聽起來更像是一個命令而不是一個問題。 PS這應該可能是[CodeReview](https://codereview.stackexchange.com) – byxor