3

Possible Duplicates:
Check if Ruby object is a Boolean
How can I avoid truthiness in Ruby?

Given an array like the following (for example):

[3, false, "String", 14, "20-31", true, true, "Other String"]

Is there an easier way to determine which elements are actual boolean values without resorting to this, for example?

value === TrueClass || value === FalseClass

Relying on the position in the array is not an option, as it will vary from case-to-case.

Community
  • 1
  • 1
dnch
  • 9,565
  • 2
  • 38
  • 41

1 Answers1

0

You could try (true & value) == value. The part in parentheses seems to always return a boolean; if the value wasn't originally a bool, then it won't be equal to the result. A bool, however, will.

cHao
  • 84,970
  • 20
  • 145
  • 172
  • 3
    Slightly simpler way is to use a double negative, ie: `!!value`. For example: `[!!true, !!false, !!nil, !!0] => [true, false, false, true]` – Kristian Holdhus Jul 11 '14 at 20:25
  • @KristianHoldhus: `!!value == value` does look less clunky. (Still need the `== value` part, though, since the point is to make sure boolifying the value didn't change it.) – cHao Jul 11 '14 at 22:04