1

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?

3 Answers 3

4
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
Sign up to request clarification or add additional context in comments.

1 Comment

Note that this assumes that you're using Rails or have required ActiveSupport's core extensions, as that's where blank? comes from. If not it can be replaced with val.nil? || val.empty?. I assumed you have Rails because of the URLs & the database reference.
2

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.

1 Comment

It's a shame the syntax highlighter gets so confused on string literals.
0

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!

1 Comment

defined? would not help in this case: gist.github.com/e76db37917284e30dbb8

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.