Ruby search words in string

I don't understand the best method to access a specific word by its number in the string.

I tried to use []

to access a word, but it returns a letter instead.

puts s 
# => I went for a walk
puts s[3]
# => w

      

+3


source to share


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


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


you can also just:

s.scan(/\w+/)[1]
=> "went" 

      

0


source


    s = "I went for a walk"
    puts   s.scan(/\w+/)[2]

    =>  for

      

If you want to access the first word, make sure you do so by referring to index 0 and so on.

eg:

s.scan(/\w+/)[0]
=> I

      

0


source







All Articles