0

I'm using Ruby 2.0 for a Rails project and am having some issues obtaining the element length of an array in the console.

First example

2.0.0-p353 :001 > search = "test"
 => "test" 
2.0.0-p353 :002 > search.split
 => ["test"] 
2.0.0-p353 :003 > search.length
 => 4 

Second example

2.0.0-p353 :001 > search = "testOne, TestTwo"
 => "testOne, TestTwo" 
2.0.0-p353 :002 > search.split(/[\s,]+/)
 => ["testOne", "TestTwo"] 
2.0.0-p353 :003 > search.length
 => 16 

How do I return the element count instead of the character count?

1
  • 1
    search.split.length => 1 Commented Dec 23, 2013 at 19:44

2 Answers 2

5

Well, you're not assigning your split array that's why you're seeing the discrepancy. What you're actually doing is defining a string search and then trying to manipulate that same string.

Try this

testArray = search.split
testArray.size
>> 1
Sign up to request clarification or add additional context in comments.

1 Comment

Np, mate! :) Merry Giftgiving Day!
2

In the first example you are getting the length of the "test" string, not of the ["test"] array. You should assign it to a variable first.

i.e.:

search = "test"       # => "test"
array = search.split  # => ["test"]
array.length          # => 1 

Comments

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.