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
如何使elophoria成为一个变量,以便如果对应的字符串为pearly或dishoria匹配并显示集合名称。像{{}}
最佳答案
回顾你所拥有的,我认为这更像是你真正想要的:
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(',')
更好,因为它允许用户在逗号后面加一个空格(例如“sad,happy”)或只使用空格(例如“sad happy”)。如您所知,
Set[]
需要多个参数。相反,我们使用Set.new
来获取值数组。或者,您可以使用mood = Set[*gets.scan(/\w+/)]
,其中*
接受值数组并将它们作为显式参数传递。另外,我从
proper_subset?
改成了subset?
,因为“happy,high”不是“happy,high”的一个子集,但它是一个子集。关于ruby - Ruby匹配子集并显示set(变量),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9046899/