I have the string "001-1776591-7", and I want to divide it into 3 parts, "-" being the split parameter.
I have already created two methods, for the first and last, but what about the second part of the string, how can I get that?
More Info:
I created the two methods in my Class, but when loading the view I get an error, details below:
def serie
@serie || cedula.to_s.split('-').[0] : @serie
end
def identificador
@identificador || cedula.to_s.split('-').[1] : @identificador
end
def verificador
@verificador || cedula.to_s.split('-').[2] : @verificador
end
SyntaxError in TecnicosController#index
/home/lurraca/Desktop/rails_project/ArLink/app/models/tecnico.rb:7: syntax error, unexpected '['
@serie || cedula.to_s.split('-').[0] : @serie
^
/home/lurraca/Desktop/rails_project/ArLink/app/models/tecnico.rb:11: syntax error, unexpected '['
...dor || cedula.to_s.split('-').[1] : @identificador
... ^
/home/lurraca/Desktop/rails_project/ArLink/app/models/tecnico.rb:15: syntax error, unexpected '['
@verificador || cedula.to_s.split('-').[2] : @verificador
The split method returns an array, so you can access the second element of it the same way you would get the second element of any other array: array[1]. Also, using the || bar can make your code simpler. Try this:
def serie
@serie || cedula.to_s.split('-')[0]
end
def banana
@banana || cedula.to_s.split('-')[1]
end
def verificador
@verificador || cedula.to_s.split('-')[2]
end
Why not set them all at once?
@serie, @identificador, @verificador = cedula.split('-')
You can make them attributes via attr_accessor or attr_reader if you still want to access them via methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With