0

I don't understand how to remove the first element of each word in an array of strings:

value = ["$6558.07", "$468.95", "$0.487526"]

and I want a array with:

value = ["6558.07", "468.95", "0.487526"]

I want to remove the $ to convert this array into an array of float to compare values, etc.

I tried this:

value.each do | value |
    value.drop(1)
end

and that just removes the entire first value.

ffouquet42
  • 124
  • 13
  • Does this answer your question? [Replace words in a string - Ruby](https://stackoverflow.com/questions/8381499/replace-words-in-a-string-ruby) – dibery Jan 20 '20 at 16:39
  • I think you didn't mean integer as those numbers have decimals too, which an integer can't hold – Viktor Jan 20 '20 at 17:05
  • 1
    `"6558.07"` is a _string_, not an integer. If you really wanted to have integers, you'd use [`to_i`](https://ruby-doc.org/core-2.7.0/String.html#method-i-to_i), or [`to_f`](https://ruby-doc.org/core-2.7.0/String.html#method-i-to_f) for floats, [`to_d`](https://ruby-doc.org/stdlib-2.7.0/libdoc/bigdecimal/rdoc/String.html#method-i-to_d) for decimals etc. – Stefan Jan 20 '20 at 17:17
  • For fun: `"$6558.07".reverse.to_f.to_s.reverse #=> "6558.07"`. – Cary Swoveland Jan 20 '20 at 18:50
  • Your question deals with a piece of a problem you are working on. You might have found answers more helpful had you addressed a larger problem in your question. For one, having a separate step that converts an array of strings to another array of strings might not be the best approach in the larger problem. I say this as food for thought when posting questions in future. – Cary Swoveland Jan 20 '20 at 19:02

2 Answers2

7

Ruby srtrings have a method which deletes a prefix:

value.map{|v| v.delete_prefix("$").to_f}
# => [6558.07, 468.95, 0.487526]
steenslag
  • 79,051
  • 16
  • 138
  • 171
1
  1. String.delete_prefix
as @steenslag answer
  1. String#delete!
values.each { |value| value.delete!('$') }
  1. String.gsub!
values.each { |value| value.gsub!(/\$/, '') }
  1. String.replace
values.each { |value| value.replace(value[1..-1]) }
  1. String.slice!
values.each { |value| value.slice!(0) }
  1. String.tr_s!
values.each { |value| value.tr_s!('$', '') }

I would recommend you read the String documentation.

Below is performance measurement with n = 10_000

               user       system     total       real
delete_prefix  0.086251   0.000000   0.086251 (  0.086255)
delete         0.096932   0.000000   0.096932 (  0.096925)
gsub!          0.141742   0.000000   0.141742 (  0.141744)
replace        0.077938   0.000000   0.077938 (  0.077942)
slice!         0.088919   0.000000   0.088919 (  0.088924)
tr_s!          0.084982   0.000000   0.084982 (  0.084988)
Thang
  • 811
  • 1
  • 5
  • 12