3
\$\begingroup\$
def users_list  
  html = ''  
  self.users.each do |user|  
    html << user.link_avatar_tag  
  end  
  html.html_safe  
end  

I feel that it is possible to write shorter.

Is it possible get rid of the temporary variable(html)?

\$\endgroup\$
  • \$\begingroup\$ What class is user? html_safe is no standard method for String - What gems are you using? Or in short: Can you provide a MWE? And to answer: It looks ok for me. \$\endgroup\$ – knut Jan 7 '13 at 15:08
  • \$\begingroup\$ Main topic of my question: Is it possible get rid of the temporary variable(html)? \$\endgroup\$ – fantgeass Jan 7 '13 at 15:30
  • \$\begingroup\$ I'll tag this rails, that's where html_safe comes from. \$\endgroup\$ – tokland Jan 7 '13 at 16:41
  • \$\begingroup\$ one question about self.users, is this a model? a helper? \$\endgroup\$ – tokland Jan 8 '13 at 8:39
  • \$\begingroup\$ This is TaskDecorator. Task has_and_belongs_to_many :users github.com/drapergem/draper \$\endgroup\$ – fantgeass Jan 8 '13 at 12:54
5
\$\begingroup\$

You should use map (don't use each to accumulate. Check this page about functional programming):

def users_list  
  users.map(&:link_avatar_get).join.html_safe
end
\$\endgroup\$
  • 1
    \$\begingroup\$ I change code a bit & that works: self.users.map(&:link_avatar_tag).join.html_safe \$\endgroup\$ – fantgeass Jan 7 '13 at 16:47
  • \$\begingroup\$ mmm, yes, you are right, here safe_join is not necessary, edited. \$\endgroup\$ – tokland Jan 7 '13 at 17:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.