Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return true if only one specific key in a hash has a true value (all the other values are false)

Tags:

ruby

hash

For instance:

options = { fight: true,
 use_item: false,
 run_away: false,
 save_game: false }

I want a boolean expression that evaluates to true iff only :fight is true, and the rest are false (as illustrated above).

I can hack this together, but I'm trying to train myself to write more elegant ruby. Thanks!

EDIT: The hack being:

(options[:fight] == true && options.delete(:fight).values.all {|x| !x})

like image 622
Kyra Westwood Avatar asked May 22 '13 18:05

Kyra Westwood


People also ask

How do you get the key of a hash in Ruby?

hash.fetch(key) { | key | block } Returns a value from hash for the given key. If the key can't be found, and there are no other arguments, it raises an IndexError exception; if default is given, it is returned; if the optional block is specified, its result is returned.

How do you return a hash in Ruby?

new : This method returns a empty hash. In the first form the access return nil. If obj is specified then, this object is used for all default values. If a block is specified, then it will be called by the hash key and objects and return the default value.

How do you check if something is a hash Ruby?

Overview. A particular value can be checked to see if it exists in a certain hash by using the has_value?() method. This method returns true if such a value exists, otherwise false .


2 Answers

Assuming all values are strictly boolean, it's as simple as:

options == {fight: true, use_item: false, run_away: false, save_game: false}

See documentation for the == method

like image 59
DanSingerman Avatar answered Oct 19 '22 18:10

DanSingerman


Inspired by Vitaliy's answer:

options[:flight] && options.values.one?
like image 43
Shawn Balestracci Avatar answered Oct 19 '22 18:10

Shawn Balestracci