Reputation: 48443
I have this simple helper:
def printe_result(data)
a_var = ('<a href="http://'+data.a_value+'>A</a>' unless (data.a_value.nil? || data.a_value.empty?))
b_var = ('<a href="http://'+data.b_value+'>B</a>' unless (data.b_value.nil? || data.b_value.empty?))
c_var = ('<a href="http://'+data.c_value+'>C</a>' unless (data.c_value.nil? || data.c_value.empty?))
return ...
end
a_value
, b_value
, c_value
I am taking from database. If the values are strings, I want to save them into the respective variable and then all variables return as one string with the values separated by comma, for example:
"<a href=http://a>A</a>, <a href=http://b>B</a>, <a href=http://c>C</a>"
How can I merge the variables only if they exist?
Upvotes: 1
Views: 218
Reputation: 96914
def printe_result(data)
{ 'A' => data.a_value, 'B' => data.b_value, 'C' => data.c_value }.map do |name, val|
"<a href='http://#{val}'>#{name}</a>" unless val.blank?
end.compact.join(',')
end
Upvotes: 4
Reputation: 84114
Something like
[[a_value,'A'],[b_value,'B'],[c_value,'C']].select {|(value, label)| !value.blank?}.
map {|(value, label)| %q[<a href="http://#{value}">#{label}</a>]}.join(',')
Ought to do the trick: use select to eliminate pairs with blank labels, map to turn the label into the desired text and join to join the strings together.
Upvotes: 2
Reputation: 5002
I hope i get your question right - you can use the defined?(variable_name)
method to check if a variable has been defined.
I hope this helps!
Upvotes: 0