Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

257
Views
Select all characters in a string until a specific character Ruby

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
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You can simply do it like this:

a.split('|').first

over 4 years ago · Santiago Trujillo Report

0

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]
over 4 years ago · Santiago Trujillo Report

0

a[/[^|]+/]
  #=> "2.452811139617034,42.10874821716908"

The regular expression simply matches as many characters other than '|' that it can.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!