So what I want is to get n characters until it hits a specific character.
i have this String :
a='2.452811139617034,42.10874821716908|3.132087902867818,42.028314077306646|-0.07934861041448178,41.647538468746916|-0.07948265046522918,41.64754863599606'
How can I make it to only get to the character | , but without getting that character, and get it like this:
2.452811139617034,42.10874821716908
You can simply do it like this:
a.split('|').first
You can avoid creating an unnecessary Array (like Array#split) or using a Regex (like Array#gsub) by using.
a = "2.452811139617034,42.10874821716908|3.132087902867818,42.028314077306646|-0.07934861041448178,41.647538468746916|-0.07948265046522918,41.64754863599606"
a[0,a.index('|')]
#=>"2.452811139617034,42.1087482171"
This means select characters at positions 0 up to the index of the first pipe (|). Technically speaking it is start at position 0 and select the length of n where n is the index of the pipe character which works in this case because ruby uses 0 based indexing.
As @CarySwoveland astutely pointed out the string may not contain a pipe in which case my solution would need to change to
#to return entire string
a[0,a.index('|') || a.size]
# or
b = a.index(?|) ? a[0,b] : a
# or to return empty string
a[0,a.index('|').to_i]
# or to return nil
a[0,a.index(?|) || -1]
a[/[^|]+/]
#=> "2.452811139617034,42.10874821716908"
The regular expression simply matches as many characters other than '|' that it can.