HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyrailsMinor

Refactor ruby each-code

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
coderefactoreachruby

Problem

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

Solution

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

Code Snippets

def users_list  
  users.map(&:link_avatar_get).join.html_safe
end

Context

StackExchange Code Review Q#20224, answer score: 5

Revisions (0)

No revisions yet.