Hi,
i am new to ruby and am facing with problem in handling string.
I have a string like
cap[?]
and i want to extract only cap, anything before <.
How can i manage to get the required string i.e. cap from cap[?].
Please help with ur suggestion.
Thanks
Saurbah
hi Saurbah,
try String#split…
string = ‘cap[?]’
array = string.split(‘<’)
puts array[0]
=> cap
check out the methods available for String here:
http://ruby-doc.org/core/classes/String.html#M001165
jake kaiden wrote in post #1007092:
array = string.split(’<’)
puts array[0]
=> cap
Hi jake,
You can add a limit argument to split(), which will make it more
efficient:
str = ‘cap[?]’
start, the_rest = str.split(’<’, 2)
puts start
–output:–
cap
Using regexes is also a way to do it:
str = ‘cap[?]’
md = str.match(/[^<]+/)
puts md[0]
–output:–
cap
7stud – wrote in post #1007143:
You can add a limit argument to split(), which will make it more
efficient:
nice one! thanks for the tip - certainly is more efficient… regex
is a good way to go too.
7stud – wrote in post #1007143:
jake kaiden wrote in post #1007092:
array = string.split(’<’)
puts array[0]
=> cap
Hi jake,
You can add a limit argument to split(), which will make it more
efficient:
str = ‘cap[?]’
start, the_rest = str.split(’<’, 2)
puts start
–output:–
cap
Using regexes is also a way to do it:
str = ‘cap[?]’
md = str.match(/[^<]+/)
puts md[0]
–output:–
cap
Thanks for the reply. It was really helpful.
There is some more complication. I have string like
str = ‘cap[?] the tap’
and i want to get
str = cap the tap
how can we do it. Please help.
Can you please tell me, the good reading material of regex. I am very
new to ruby.
Thanks. Please help me.
Saurabh A. wrote in post #1007238:
str = ‘cap[?] the tap’
and i want to get
str = cap the tap
how can we do it. Please help.
str = ‘cap[?] the tap’
pieces = str.split(/
<
.+
>
/xms)
puts pieces.join
–output:–
cap the tap
Can you please tell me, the good reading material of regex. I am very
new to ruby.
Beginning Ruby: From Novice to Professional (2nd) by Cooper
Programming Ruby 1.9
And there are plenty of tutorials on the web.