Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails (or Ruby): Yes/No instead of True/False

I know I could easily write a function and put it in the application controller, but I'd rather not if there is something else that does this already. Basically I want to have something like:

>> boolean_variable? => true >> boolean_variable?.yesno => yes >> boolean_variable?.yesno.capitalize => Yes 

is there something like this already in the Rails framework?

like image 557
aarona Avatar asked Sep 08 '10 02:09

aarona


People also ask

Is true or false in Ruby?

Every object in Ruby has a boolean value, meaning it is considered either true or false in a boolean context. Those considered true in this context are “truthy” and those considered false are “falsey.” In Ruby, only false and nil are “falsey,” everything else is “truthy.”

What evaluates to false in Ruby?

in a boolean context (if, &&, ||, etc.). Ruby has to decide whether these values count as true or false. If the value isn't literally "true" but evaluates as true, we call it "truthy." Likewise, if the value isn't literally "false" but evaluates as false, we call it "falsey."

Is False an object in Ruby?

In Ruby, true and false are boolean values that represent yes and no. true is an object of TrueClass and false is an object of FalseClass.


1 Answers

There isn't something in Rails.

A better way than adding to the true/false classes to achieve something similar would be to make a method in ApplicationHelper:

def human_boolean(boolean)     boolean ? 'Yes' : 'No' end 

Then, in your view

<%= human_boolean(boolean_youre_checking) %> 

Adding methods to built-in classes is generally frowned upon. Plus, this approach fits in closely to Rails' helpers like raw().

Also, one offs aren't a great idea as they aren't easily maintained (or tested).

like image 124
Neal Avatar answered Sep 18 '22 15:09

Neal