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

Viewed 27131

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?

6 Answers

I love the generalised solutions in the previous answers, but if you want to selectively use a humanised version of your boolean in your views, you could do the following:

I put this into helpers/application_helper.rb:

module ApplicationHelper

  def humanize_boolean(value)
    case value
    when true
      "Yes"
    when false
      "No"
    when nil
      "Undefined"
    else
      "Invalid"
    end
  end

end

Then from views you can call it as in this example:

Published: <%= humanize_boolean(post.published) %>
Related