Strictly convert string to integer (or nil)
Use Integer(string)
It will raise an ArgumentError error if the string cannot convert to an integer.
Integer('5abc') #=> ArgumentError: invalid value for Integer(): "5abc"
Integer('5') #=> 5
You'd still need your number_or_nil method if you want the behavior to be that nil is returned when a string cannot be converted.
def number_or_nil(string)
Integer(string || '')
rescue ArgumentError
nil
end
You should be careful to rescue from a particular exception. A bare rescue (such as "rescue nil") will rescue from any error which inherits from StandardError and may interfere with the execution of your program in ways you don't expect. Integer() will raise an ArgumentError, so specify that.
If you'd rather not deal with exceptions and just prefer a shorter version of your number_or_nil you can take advantage of implicit return values and write it as:
def number_or_nil(string)
num = string.to_i
num if num.to_s == string
end
number_or_nil '5' #=> 5
number_or_nil '5abc' #=> nil
This will work the way you expect.
rails convert string to number
.to_f
is the right way.
Example:
irb(main):001:0> "-10".to_f
=> -10.0
irb(main):002:0> "-10.33".to_f
=> -10.33
Maybe your string does not include a regular "-" (dash)? Or is there a space between the dash and the first numeral?
Added:
If you know that your input string is a string version of a floating number, eg, "10.2", then .to_f is the best/simplest way to do the conversion.
If you're not sure of the string's content, then using .to_f
will give 0 in the case where you don't have any numbers in the string. It will give various other values depending on your input string too. Eg
irb(main):001:0> "".to_f
=> 0.0
irb(main):002:0> "hi!".to_f
=> 0.0
irb(main):003:0> "4 you!".to_f
=> 4.0
The above .to_f
behavior may be just what you want, it depends on your problem case.
Depending on what you want to do in various error cases, you can use Kernel::Float
as Mark Rushakoff suggests, since it raises an error when it is not perfectly happy with converting the input string.
convert string number with bytes to integer in rails (32MB - 32.megabytes)
There's filesize
It's quite trivial to write your own:
But you can write your own:
def convert_size_to_bytes
md = match(/^(?<num>\d+)\s?(?<unit>\w+)?$/)
md[:num].to_i *
case md[:unit]
when 'KB'
1024
when 'MB'
1024**2
when 'GB'
1024**3
when 'TB'
1024**4
when 'PB'
1024**5
when 'EB'
1024**6
when 'ZB'
1024**7
when 'YB'
1024**8
else
1
end
end
Convert string to number in where clause
ActiveRecord where accepts string
as query constructor
OnlineCourseRegistration.where("course_class_id = ? AND status = ? AND score > ?", 681, "Completed", 70).last
Convert field from integer to string in one rails Active Record relation before sending json
All Rails models have an as_json
method that gets called when rednering the model to JSON. You can override this method within your models to set up custom JSON formatting. In your case, you may want to add something like this to your Wine
model:
def as_json(opts = {})
json = super(opts)
json["grape_id"] = self.grape_id.to_s
json
end
The method gives you the default model JSON when you call the super
method and set it to the json
variable, then stringifies grape_id
and sets it in the JSON, and finally returns the updated JSON.
Now, any time a controller returns a JSON version of single Wine model, or an association of multiple Wine models, the JSON will be formatted through this updated method and the grape_id
will be stringified every time.
Convert array of strings to an array of integers
To convert a string to number you have the to_i
method.
To convert an array of strings you need to go through the array items and apply to_i
on them. You can achieve that with map
or map!
methods:
> ["", "22", "14", "18"].map(&:to_i)
# Result: [0, 22, 14, 18]
Since don't want the 0
- just as @Sebastian Palma said in the comment, you will need to use an extra operation to remove the empty strings: (The following is his answer! Vote for his comment instead :D)
> ["", "22", "14", "18"].reject(&:empty?).map(&:to_i)
# Result: [22, 14, 18]
the difference between map
and map!
is that map
will return a new array, while map!
will change the original array.
Convert string to int array in Ruby
A simple one liner would be:
s.each_char.map(&:to_i)
#=> [2, 3, 5, 3, 4]
If you want it to be error explicit if the string is not contained of just integers, you could do:
s.each_char.map { |c| Integer(c) }
This would raise an ArgumentError: invalid value for Integer():
if your string contained something else than integers. Otherwise for .to_i
you would see zeros for characters.
Related Topics
How to Check If a Number Is Included in a Range (In One Statement)
Get Today's Date in Jekyll with Liquid Markup
Ruby on Rails: Errors.Add_To_Base VS. Errors.Add
When Is It Better to Use a Struct Rather Than a Hash in Ruby
Rails Development Server Is Slow and Takes a Long Time to Load a Simple Page
How to Filter an Array of Hashes to Get Only the Keys in Another Array
Ubuntu 12 - How to Install Ruby and Rails Correctly
Ruby on Rails, Could Not Find a Valid Gem 'Rails'
Rails Console Running Incredibly Slowly When Editing Text
Uninstall Ruby Version from Rbenv
Rails Flash Message Remains for Two Page Loads
How to Load a Spec_Helper.Rb Automatically in Rspec 2
How to Recompile a Ruby with Rvm
Adding an Instance Variable to a Class in Ruby
Is There a Good Admin Generator for Ruby on Rails
How to Update Gems on Production Server
Using Ruby's Optionparser to Parse Sub-Commands
What Is the Second Parameter/Argument to CSV.Open( ) in Ruby