Ruby: How to convert a string to boolean
def true?(obj)
obj.to_s.downcase == "true"
end
String true and false to boolean
As far as i know there is no built in way of casting strings to booleans,
but if your strings only consist of 'true'
and 'false'
you could shorten your method to the following:
def to_boolean(str)
str == 'true'
end
Converting anything to a boolean in Ruby
No, !!
is the cleanest way.
If you're on Rails however, you could check out object.present?
. It returns false
for all of the following:
false
nil
""
[]
{}
The last three return true
with !!
but will return false
with present?
.
How to change my boolean output to a string value in ruby
Just use a ternary:
reply.rsvp ? "true" : "false"
Replace "true" and "false" by whatever strings you want to display.
Convert true-false strings to boolean & Skip the rest in a hash
I think this does what you want. I have not calculated the O of it.
I used the Marshal#dump/load trick to do a deep copy of the object before manipulating it.
mp = "most_popular"
obj = Marshal.load(Marshal.dump(h))
obj.each_key {|k| obj[k].each {|v| v[mp] = v[mp] == "true" ? true : false if v[mp] }}
Also see Cary's comment below for a slightly more terse version of the inner block.
In Rails, how can I get a string from a boolean?
You can use my_boolean_value.to_s
. Basically it will convert booleans to string.
You can also do "#{my_boolean_value}"
Note: If my_boolean_value
can be .nil?
or anything other then true/false
then your solution in the question is the best and simplest way to do it. You can use following way as well if you don't want to use ternary operator,
(!!my_boolean_value).to_s
But I still think from readability and maintainability point of view, you should use the solution given in the question. Reason would be, you are doing double negation can be confusing if you don't put comments around.
Need to convert a Boolean from Postgres (== String) to a Ruby Boolean
ActiveRecord has a method called ActiveRecord::ConnectionAdapters::Column.value_to_boolean
it uses internally to convert any true-like value to a Ruby true
value.
You can use it in your code.
Related Topics
In Rails - Is There a Rails Method to Convert Newlines to <Br>
Database Configuration Does Not Specify Adapter
How to Detect Certain Unicode Characters in a String in Ruby
How to Fix Rubygems Recent Deprecation Warning
How to Download via Http Only Piece of Big File with Ruby
How to Check for File Existence
Gem Install Pg Doesn't Work on Osx Lion
How to Get the Current Time as 13-Digit Integer in Ruby
"Whenever" Gem Running Cron Jobs on Heroku
Ruby on Rails - Drop Down Box on Change Event
How to Remove Permission Denied @ Rb_Sysopen - Gem Install Error
Differencebetween 'Range#Include' and 'Range#Cover'
Select Arrays Between Date Ranges with Ruby