Ruby search words in string
4 answers
What you are doing will have access to the fourth character of the string s
.
Split the string into an array and then access the fourth element as follows.
puts s.split[3]
Note. Calling split without parameters splits the string at whitespace.
Edit: fixing the indices. The index starts at 0. This means that s.split [3] will access the fourth element.
+4
source to share
You are asking for the fourth character from the string, since you start counting at 0
p "I went for a walk"[3]
# "e"
You can split the string into words instead, but don't just use split on yourself, because it will only split on space, whereas normally you should split all word boundaries with a little regex. Then you remove any empty items caused by commas and other borders.
p "I went for a walk, it was warm outside".split(/\W/).reject(&:empty?)
# ["I", "went", "for", "a", "walk", "it", "was", "warm", "outside"]
p "I went for a walk, it was warm outside".split(/\W/).reject(&:empty?)[1]
# "went"
+1
source to share