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)?

tokland
11.2k1 gold badge21 silver badges26 bronze badges
asked Jan 7, 2013 at 13:43
\$\endgroup\$
6
  • \$\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\$ Commented Jan 7, 2013 at 15:08
  • \$\begingroup\$ Main topic of my question: Is it possible get rid of the temporary variable(html)? \$\endgroup\$ Commented Jan 7, 2013 at 15:30
  • \$\begingroup\$ I'll tag this rails, that's where html_safe comes from. \$\endgroup\$ Commented Jan 7, 2013 at 16:41
  • \$\begingroup\$ one question about self.users, is this a model? a helper? \$\endgroup\$ Commented Jan 8, 2013 at 8:39
  • \$\begingroup\$ This is TaskDecorator. Task has_and_belongs_to_many :users github.com/drapergem/draper \$\endgroup\$ Commented Jan 8, 2013 at 12:54

1 Answer 1

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
answered Jan 7, 2013 at 16:36
\$\endgroup\$
2
  • 1
    \$\begingroup\$ I change code a bit & that works: self.users.map(&:link_avatar_tag).join.html_safe \$\endgroup\$ Commented Jan 7, 2013 at 16:47
  • \$\begingroup\$ mmm, yes, you are right, here safe_join is not necessary, edited. \$\endgroup\$ Commented Jan 7, 2013 at 17:05

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.