Ruby匹配子集和显示集(变量)

时间:2012-01-28 16:37:06

标签: ruby set subset

feelings = Set["happy", "sad", "angry", "high", "low"]
euphoria = Set["happy", "high"]
dysphoria = Set["sad", "low"]
miserable = Set["sad", "angry"]

puts "How do you feel?"
str = gets.chomp
p terms = str.split(',')

if euphoria.proper_subset? feelings
  puts "You experiencing a state of euphoria."
else
  puts "Your experience is undocumented."
end

gets

如何将欣快感变成一个变量,这样如果对应的悲惨或烦躁的字符串匹配&显示集名称。喜欢#{Set}

2 个答案:

答案 0 :(得分:2)

每当您认为要将变量的名称放入另一个变量时,您可能需要使用Hash:

states = {
    'euphoria'  => Set["happy", "high"],
    'dysphoria' => Set["sad",   "low"],
    'miserable' => Set["sad",   "angry"]
}

然后你可以这样说:

which = 'euphoria' # Or where ever this comes from...
if states[which].proper_subset? feelings
  puts "You experiencing a state of #{which}."
else
  puts "Your experience is undocumented."
end

答案 1 :(得分:2)

回顾你拥有的东西,我认为这更像你真正想要的东西:

require 'set'

feelings = {
  euphoria: Set.new(%w[happy high]),
 dysphoria: Set.new(%w[sad low]),
 miserable: Set.new(%w[sad angry])
}

puts "What are you feeling right now?"
mood = Set.new gets.scan(/\w+/)
name, _ = feelings.find{ |_,matches| matches.subset?( mood ) }
if name
  puts "You are experiencing a state of #{name}"
else
  puts "Your experience is undocumented."      
end

调用gets.scan(/\w+/)会返回一个字符串数组。它比.split(',')更好,因为它允许用户在逗号之后添加空格(例如“悲伤,快乐”)或仅使用空格(例如“悲伤快乐”)。

如您所知,Set[]需要多个参数。相反,我们使用Set.new来获取值数组。或者,您可以使用mood = Set[*gets.scan(/\w+/)],其中*获取值数组并将它们作为显式参数传递。

此外,我从proper_subset?更改为subset?,因为“happy,high”不是“happy,high”的正确的子集,但它是子集。