I am trying to concat
two strings that are returned by a function to two existing strings in one line.
this is my code with extra steps
def my_function()
return "foo", "bar"
end
foo = String.new
bar = String.new
ret1, ret2 = my_function()
foo.concat(ret1)
bar.concat(ret2)
I am trying something like the following, but it is not working
foo.concat(ret1), bar.concat(ret2) = my_function()
some more information as requested:
I am basically trying to write a config converter. The config files need to be plain text files. To make the code more structured, i created the following module, and then call the module functions whenever i need to genereate a specific part of the config. After that, I write the return into a string, which is then written to a file once everything is done:
module L4_LB
extend self
def build_ssl(some_vars)
returns string_a, string_b
end
def build_vip(some_vars)
returns string_a, string_b
end
def build_pool(some_vars)
returns string_a, string_b
end
end
config_file_a = String.new
config_file_b = String.new
ret_a, ret_b = L4_LB.build_ssl(some_vars)
config_file_a.concat(ret_a)
config_file_a.concat(ret_b)
ret_a, ret_b = L4_LB.build_vip(some_vars)
config_file_a.concat(ret_a)
config_file_a.concat(ret_b)
ret_a, ret_b = L4_LB.build_pool(some_vars)
config_file_a.concat(ret_a)
config_file_a.concat(ret_b)
CodePudding user response:
It depends on how concat
is defined. If it accepts multiple arguments, you should be able to do:
config_file_a.concat(*L4_LB.build_pool(some_vars))
Note the *
which ensures that each element in the array returned by build_pool
is passed as an individual argument to concat.
On the other hand, if concat
only accepts a single argument you can define a helper function:
def my_concat(what, values)
values.each do |element|
what.concat(element)
end
end
my_concat(config_file_a, L4_LB.build_pool(some_vars))
If you want the result to be concatenated to two different strings, you could use:
def my_concat2(cs, vs)
cs.each_with_index do |c, index|
c.concat(vs[index])
end
end
cs = [config_file_a, config_file_b]
my_concat2(cs, *L4_LB.build_ssl(some_vars))
my_concat2(cs, *L4_LB.build_vip(some_vars))
my_concat2(cs, *L4_LB.build_pool(some_vars))