On Sat, Oct 13, 2012 at 1:35 PM, Roelof Wobben <[email protected]> wrote:
> Hello,
>
> Suppose I have 3 arrays with content. The content are articles of that
> category.
> Now I want 1 of the 3 arrays displayed and the other 2 not.
> Which array depends on the content.
>
> Now I can make 3 times this code.
>
> category1.article.each do |artikel|
>     puts article.name
> end
>
> category2.article.each do |artikel|
> puts article.name
> end
>
> category3.article.each do |artikel|
> puts article.name
> end
>
> But now I have 3 parts of code which are almost the same.
> Is there a way I can make 1 part of code where the category is a variable.

The usual solution for repeated code is to put it into a function or
method and pass appropriate arguments.  So you could do

def show_category(cat)
  cat.each do {|article| puts article.name}
end

You could also do

puts category.article.map(&:name)

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

-- You received this message because you are subscribed to the Google Groups 
ruby-talk-google group. To post to this group, send email to 
[email protected]. To unsubscribe from this group, send email 
to [email protected]. For more options, visit this 
group at https://groups.google.com/d/forum/ruby-talk-google?hl=en

Reply via email to