0

I am matching a pattern and i need to split and push it into an array.

a = Array.new
doc = "<span>Hi welcome to world</span>"
len = doc.length
puts doc.scan(/o/)
a << doc.scan(/o/)
puts a.length

Output for the above code is

o
o
o
1

The length of array is 1

I want the length of array to be 3

Instead of pushing a complete string into an array. i want to push it as three different elements

3
  • try a << firstString << secondString ... ? Commented Jan 13, 2015 at 7:09
  • Why do you expect the length of the array to be 4? Commented Jan 13, 2015 at 7:45
  • Fyi. You pushed an array into array. So a has a second element which is the array produced from doc.scan(/o/). Commented Jan 13, 2015 at 9:29

1 Answer 1

2

You need to use Array#concat method.

a = Array.new
doc = "<span>Hi welcome to world</span>"
len = doc.length
puts doc.scan(/o/)
a.concat doc.scan(/o/)
puts a.length # => 3

doc.scan(/o/) gives you ['o', 'o', 'o']. And a << doc.scan(/o/) gives you [['o', 'o', 'o']], not ['o', 'o', 'o']. That's why you are getting the size of a as 1.

What you want to achieve can be made using Array#concat. Because a.concat doc.scan(/o/) will give you exactly ['o', 'o', 'o'], and thus size of a is now 3.

But you could write it as:

doc = "<span>Hi welcome to world</span>"
len = doc.length
puts doc.scan(/o/)
a = doc.scan(/o/)
puts a.length # => 3

Looking at your this mini code a = Array.new is not needed.

Sign up to request clarification or add additional context in comments.

3 Comments

also maybe simply a += doc.scan(/o/) ?
@shivam It will create a new object.. :)
You could also pass a block to scan: doc.scan(/o/) { |m| a << m }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.