3

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...

2 Answers 2

5

Why not test in the call to map?

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

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

1 Comment

I copied your code and ran that. But it's giving me an error saying: syntax error, unexpected '='. So I changed it to "=~" rather than "~=".But this time again it's crating the same array with "http://yahoo.com"...that again adding an extra "http://" before the element.
0

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.

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.