byCoder
byCoder

Reputation: 9184

Rails check string for symbols

I'm nubbie in rails and ruby In my app i get data from csv and in some fields of quantities value is 100> and etc. But how to check that? and select only integer(float) part? But note! it can be <20, >30, 30< and so over.

Upvotes: 0

Views: 150

Answers (2)

Anupam
Anupam

Reputation: 1530

If you have floating point numbers (not just the integer part), you can use a small variant of Justin Ko's solution:

values = ["10.1>", "<20.3", ">30.4", "30.6<"]
values.each do |val|
  puts /(\d+\.\d+)/.match(val)[0].to_f
end

# => Output will be 10.1 20.3 30.4 30.6    

Upvotes: 1

Justin Ko
Justin Ko

Reputation: 46836

You can use a regex to just get the numeric part of the field.

The regex is simply /(\d+)/.

Here is an example:

values = ['<20', '>30', '30<']
values.each do |val|
    puts /(\d+)/.match(val)[0].to_i
end
# => 20, 30, 30

Upvotes: 0

Related Questions