【问题标题】:Ruby matching subsets and displaying set(variable)Ruby 匹配子集并显示集合(变量)
【发布时间】:2012-01-28 16:37:06
【问题描述】:
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 设为变量,这样如果对应的 miserable 或 dysphoria 字符串匹配并显示集合名称。喜欢#{Set}

【问题讨论】:

    标签: ruby set subset


    【解决方案1】:

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

    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”的正确子集,但它是一个子集。

    【讨论】:

    • 我想要它不仅仅是为了兴奋,而是显示这三个中的任何一个或者如果用户输入匹配。 if states.include? feelings; puts "You experiencing a state of #{states}."; else; puts "Your experience is undocumented."; end 我猜;
    • @user1125021 也许你在我编辑它之前看过我的代码。再看一遍。
    【解决方案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
    

    【讨论】:

    • 'uninitialized constant Set (NameError)' 欣快来自terms,so which = terms
    • @user1125021 您需要require "set" 才能使用Set 库,因为它是Standard Library 的一部分(包含在Ruby 安装中,但默认情况下不包含在运行时中)和不是Core(它是运行时的一部分)。
    • 我得到这个错误:未定义的方法proper_subset?对于 nil:NilClass (NoMethodError)。我认为proper_subset?在 stdlib 中预定义了 #{which}." 中的 #{ 在我的 IDE 中突出显示
    • @user1125021:您在nil 上调用proper_subset?,因此您的whichterms(或您使用的任何名称)不正确,您可能需要添加@ 987654333@检查。
    • proper_subset? 不是标准库的一部分。它是Set 的一部分。同样,您需要require 'set'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    相关资源
    最近更新 更多