Siddharth
Siddharth

Reputation: 893

Iterate through array using Map and Select method Together in Ruby

I am developing an application where I'm stuck with the following code.

I have an array of links which is holding some links posted by a user in a form. say for example my array is bunch1 = ["google.com","http://yahoo.com"]

Now, before I store them into database I need to make sure that each link has "http://" added at the beginning because I have 'validate:' logic in my ActiveRecord object.

So my logic is that I will iterate through the array and check if "http://" string segment present before each link in the array. So clearly I have to add "http://" string segment before "google.com" in my array.

So I have written a code like this:

bunch2=bunch1.map { |y| y="http://"+y }

But it creates a bunch2 array like bunch2=["http://google.com","http://http://yahoo.com"]

As you can see it adds an extra "http://" before "http://yahoo.com" .

To solve this problem I modified the above code like this:

bunch2 = bunch1.select { |x|  x !~ /http/ }.map { |y| y="http://"+y }

but it's generating a array like bunch2 = ["http://google.com"] because the regular expression with select method is eliminating the yahoo.com

Can somebody please give me solution for this problem. Thanks in advance...

Upvotes: 3

Views: 598

Answers (2)

Ron Warholic
Ron Warholic

Reputation: 10074

Why not test in the call to map?

bunch2 = bunch1.map {|y| y !~ /^http/ ? "http://#{y}" : y }

Upvotes: 5

Siddharth
Siddharth

Reputation: 893

Ok, guys I have found the solution to this problem. So the code don't need a select method at all. It just needs a ternary operator for this. So my one liner code goes like this:-

@[email protected] { |x| x.match(/http:/) ? x : "http://"+x }

The above code using the match method for matching with regular expression. If it finds a match then the element is unchanged otherwise the "httP://" string is added at the beginning.

Upvotes: 0

Related Questions