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.
How to convert a string of ids inside an array to array of ids without string in ruby?
You're trying to split an array, try to split a string instead:
["4,5,6"].first.split(',')
#=> ["4", "5", "6"]
After that you can simply convert it to an array of ints:
["4", "5", "6"].map(&:to_i)
#=> [4, 5, 6]
How to convert an array of string integers to an array of integers? Ruby
all_ages = ["11", "9", "10", "8", "9"]
Code
p all_ages.map(&:to_i).sum
Or
p all_ages.map { |x| x.to_i }.sum
Output
47
How to convert an array of integers to an integer
[nil, 3, 4, 2].join.to_i
#=> 342
Return an array with integers in stead of strings
newArray <<"#{total}" # WRONG
You're pushing strings into the array with the expectation of getting integers in the end. Change the above line to:
newArray << total
And just FYI, you can use map
to clean things up here.
def your_method(array)
array.map.with_index do |element, index|
element + index
end
end
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.
Ruby array to string conversion
I'll join the fun with:
['12','34','35','231'].join(', ')
# => 12, 34, 35, 231
EDIT:
"'#{['12','34','35','231'].join("', '")}'"
# => '12','34','35','231'
Some string interpolation to add the first and last single quote :P
Related Topics
Rake Assets:Precompile Attempting to Connect to Database
Is There a Simple Way to Get Image Dimensions in Ruby
Hash Ordering Preserved Between Iterations If Not Modified
How to Format a Number 1000 as "1 000"
Sidekiq Not Deallocating Memory After Workers Have Finished
Rails3 Devise Undefined Method 'Confirmation_Url'
How to Backreference in Ruby Regular Expression (Regex) with Gsub When I Use Grouping
How to Get My MAChine's Ip Address from Ruby Without Leveraging from Other Ip Address
Error Installing Debugger: Failed to Build Gem Native Extension with Ruby-1.9.3-P362
Why Alias_Method Fails in Rails Model
How to Reverse Ruby's Include Function