Reality is a Fractal
Reality is a Fractal

Reputation: 67

Ruby matching subsets and displaying set(variable)

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}

Upvotes: 2

Views: 318

Answers (2)

Phrogz
Phrogz

Reputation: 303261

Reviewing what you have, I think this is more like what you really want:

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

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 use Set.new which takes an array of values. Alternatively, you could have used mood = Set[*gets.scan(/\w+/)], where the * takes the array of values and passes them as explicit parameters.

Also, I changed from proper_subset? to just subset?, because "happy,high" is not a proper subset of "happy,high", but it is a subset.

Upvotes: 2

mu is too short
mu is too short

Reputation: 434685

Whenever you think you want to put the name of a variable into another variable, you probably want a Hash instead:

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

Then you can say things like:

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

Upvotes: 2

Related Questions