prajeesh
prajeesh

Reputation: 2382

Split a string into two

How can I split strings as follows?

"1 Bedroom / 1 1/2 Bath"
# ... => ["1 Bedroom ", "1 1/2 Bath"]

"1 Bedroom / 1/2 Bath"
# ... => ["1 Bedroom ", "1/2 Bath"]

I tried:

"1 Bedroom / 1 1/2 Bath".split('/')
# => ["1 Bedroom ", " 1 1", "2 Bath"]

Upvotes: 0

Views: 89

Answers (4)

sawa
sawa

Reputation: 168101

"1 Bedroom / 1 1/2 Bath".split("/ ", 2)
# => ["1 Bedroom ", "1 1/2 Bath"]

"1 Bedroom / 1/2 Bath".split("/ ", 2)
# => ["1 Bedroom ", "1/2 Bath"]

Upvotes: 0

Rajagopalan
Rajagopalan

Reputation: 6064

If you specify 2 as a second paramether to the split method, then it would do the way you intended.

a="1 Bedroom / 1 1/2 Bath"
p a.split('/',2)

Result

["1 Bedroom ", " 1 1/2 Bath"]

and this one would strip the trailing and leading space for each string in the array

p a.split("/",2).map(&:strip)

Result

["1 Bedroom", "1 1/2 Bath"]

Upvotes: 2

Ashik Salman
Ashik Salman

Reputation: 1879

Try with adding spaces:

str = "1 Bedroom / 1 1/2 Bath"
str.split(' / ') 

Upvotes: 2

Try:

"1 Bedroom / 1 1/2 Bath".split(' / ')

Upvotes: 3

Related Questions