Reputation: 2382
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
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
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
Reputation: 1879
Try with adding spaces:
str = "1 Bedroom / 1 1/2 Bath"
str.split(' / ')
Upvotes: 2