YoYoYo I'm Awesome YoYoYo I'm Awesome - 2 months ago 11
Ruby Question

How to inject characters into an array, and join that array into a string?

I have a url that's split by

=
parameters, what I want to do is inject characters into the array after every
=
:

For example:

http://multiplexstimulator.com/catalog/product.php?cat_id=82&pid=157&view=print


Should be split by the equals sign into an array that looks like this:
["http://multiplexstimulator.com/catalog/product.php?cat_id", "=", "82&pid", "=", "157&view", "=", "print"]


Then I want to add the letter "a" after the equals signs:

["http://multiplexstimulator.com/catalog/product.php?cat_id", "=", "a", "82&pid", "=", "a", "157&view", "=", "a", "print"]


After this is done I want to
join
that array to output:
"http://multiplexstimulator.com/catalog/product.php?cat_id=a82&pid=a157&view=aprint"
.

What I've tried:

module MultipleParameters

class TestAllParameters

def check_for_multiple_parameters(site, char)
site_arr = []
if site.count("=") != 1
site.split("=").each do |string_split|
site_arr.push(string_split)
end
end

inject_syntax(site_arr, char)
end

def inject_character(array, char)
array.each do |param|
param.inject(char)
end

puts array.join("")
end

end

end


However when I do this, I'm getting the error:

detection.rb:18:in `block in inject_syntax': undefined method `inject' for "http://multiplexstimulator.com/catalog/product.php?cat_id":String (NoMethodError)
Did you mean? inspect
from detection.rb:17:in `each'
from detection.rb:17:in `inject_syntax'
from detection.rb:13:in `check_for_multiple_parameters'
from detection.rb:33:in `<main>'


How can I do this successfully? Will I need to
scan
the string and split it when there's a "=" found instead of splitting the string by the equals sign?

Answer

Firstly you should separate params from url

url = 'http://multiplexstimulator.com/catalog/product.php?cat_id=82&pid=157&view=print'

array = url.split('/')

and now you should change all '=' to '=a' in last element in this array

array[-1] = array[-1].gsub('=', '=a')

now you can use join on this array :)

new_url = array.join('')