Ruby 匹配子集并显示集合(变量)
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
如何使 euphoria 成为一个变量,这样如果悲惨或烦躁的相应字符串匹配 &显示设定名称。就像#{设置}
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
How do I make euphoria a variable, such that if the corresponding string for miserable or dysphoria match & display the set name. Like #{Set}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
回顾一下你所拥有的,我认为这更像是你真正想要的:
调用 gets.scan(/\w+/) 返回一个字符串数组。它比
.split(',')
更好,因为它允许用户在逗号后面添加空格(例如“sad, happy”)或仅使用空格(例如“sad happy”)。正如您所知,
Set[]
需要多个参数。相反,我们使用 Set.new 它接受一个值数组。或者,您可以使用mood = Set[*gets.scan(/\w+/)]
,其中*
获取值数组并将它们作为显式参数传递。另外,我从
proper_subset?
更改为subset?
,因为“happy,high”不是“happy,high”的正确子集,但它是一个子集。Reviewing what you have, I think this is more like what you really want:
Calling
gets.scan(/\w+/)
returns an array of strings. It's better than just.split(',')
because it allows the user to put a space after commas (e.g. "sad, happy") or just use spaces (e.g. "sad happy").As you already know,
Set[]
requires multiple arguments for it. Instead, we useSet.new
which takes an array of values. Alternatively, you could have usedmood = Set[*gets.scan(/\w+/)]
, where the*
takes the array of values and passes them as explicit parameters.Also, I changed from
proper_subset?
to justsubset?
, because "happy,high" is not a proper subset of "happy,high", but it is a subset.每当您认为要将一个变量的名称放入另一个变量时,您可能需要一个哈希值:
然后您可以这样说:
Whenever you think you want to put the name of a variable into another variable, you probably want a Hash instead:
Then you can say things like: