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})
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.
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.
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 .
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
Inspired by Vitaliy's answer:
options[:flight] && options.values.one?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With