Iterate over a string with #split method, how to get the total number of elements

I have the following code

s = 'string1, string2, string3, string4'

s.split(",").each_with_index{ |element, index| puts "line #{index} of #{size_of_array}" }

What is the best way to get the size of the array ? Is there a method that I can call on the same line of the split passing to the loop ?


I think you're looking for tap:

s.split(',').tap{|a| a.size.times{|i| puts "line #{i} of #{a.size}"}}

but really, just a ; keeps as much as you want on the same line:

a = s.split(','); a.size.times{|i| puts "line #{i} of #{a.size}"}

Notice size instead of length because it's 2 chars shorter.

Need Your Help

How to launch a native OSX app (and pass parameters) from the web?

objective-c cocoa osx url

I'm trying to launch a MacOSX app from a website and pass an authentication token from the web server. I'm trying to do something like myNewURLScheme://myauthtoken (similar to the iTunes itms:// UR...

Creating Function with Generic Return Type

c# generics types

Currently i am having following function

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.