Hi StackOverflow Community.
I have the following table with two tables "id" (integer) and "num_pot" (varchar 255) with the following data information:
|transformers|
|id| |num_pot|
1 1.0
2 2.12/6
3 5/6/8
4 2.9/40
5 2.1
Here is the transformer_controller.rb, it displays all registries
def index
@transformers = Transformer.all
end
I'm trying to display the following information on my array view index.html.erb
<% @transformers.each do |array| %>
<%= array.num_pot %>
<% end %>
I'm trying to create the code to check on strings and compare on the column num_pot:
|num_pot|
1.0 # CHECK THE GREATEST VALUE = 1.0
2.12/6 # CHECK THE GREATEST VALUE = 6
5/6/8 # CHECK THE GREATEST VALUE = 8
2.9/40 # CHECK THE GREATEST VALUE = 40
2.1 # CHECK THE GREATEST VALUE = 2.1
How can I display the following data (the maximum value on string):
|num_pot|
1.0
6
8
40
2.1
I tried the following code using "max" but I got error:
<% @transformers.each do |array| %>
<%= array.num_pot.max(1) %>
<% end %>
undefined method `max' for "2.12/6":String
I would appreciate any comments about it
The values in your num_pod
column are as you already wrote – strings and not a list of numbers. That means, to only render one of the values and only the biggest of them, you first need to split the string into its parts. And then translate the parts into floats to be able to compare and pick the biggest value.
Let's take this example:
'5.2/6/8'.split('/')
#=> ['5.2', '6', '8']
'5.2/6/8'.split('/').map(&:to_f)
#=> [5.2, 6, 8]
'5.2/6/8'.split('/').map(&:to_f).max
#=> 8
The last two steps can be simplified to just max_by(&:to_f)
, because in your case it would be okay, to compare them values by their float value but to return their string values to be rendered.
Using this, you should get the expected result by changing the view to:
<% @transformers.each do |transformer| %>
<%= transformer.num_pot.split('/').max_by(&:to_f) %>
<% end %>
Or, to make it easier to read in the view and reusable, add this method to your Transformer
model in app/models/transformer.rb
:
def max_num_pot
num_pot.split('/').max_by(&:to_f)
end
And change the view to:
<% @transformers.each do |transformer| %>
<%= transformer.max_num_pot %>
<% end %>