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...
Why not test in the call to map?
bunch2 = bunch1.map {|y| y !~ /^http/ ? "http://#{y}" : y }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With