How do I split a string into three parts?
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.
cedula.to_s.split('-')[1]
split returns an array.
cedula.to_s.split('-')[0] is the same as cedula.to_s.split('-').first
cedula.to_s.split('-')[1] is the second part of your string
cedula.to_s.split('-').last is the last part in this case the third which can be accessed        via: cedula.to_s.split('-')[2] as well
> cedula.to_s.split('-')
=> ["001", "1776591", "7"]
Split splits a string into an Array. Elements of an array can be accessed the following way:
array[0], array[1] etc...
An array begins from 0.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论