Multiple array problem

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.nameend
category2.article.each do |artikel| puts article.nameend
category3.article.each do |artikel| puts article.nameend 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. Roelof

Hi,

first select the right category and iterate over the articles
afterwards.

For example:

cat_id = 2
category =
case cat_id
when 1
category1
when 2
category2
else
category3
end
category.article.each {|art| puts art.name}

It would actually be better if you’d store the different category
objects in a structured way (like in a array). That would make selecting
them much easier.

You mean a array which contains the array.
That I have but as I said I need one category a time.

Roelof

On Sat, Oct 13, 2012 at 7:35 AM, Roelof W. [email protected]
wrote:

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.

Sure. Make an array out of your 3 arrays: [category1, category2,
category3]. Then call .each on THAT. E.g.:

[category1, category2, category3].each do |category|
category.article.each do |article|
puts article.name
end
end

Not sure where you’re getting category.article from though; is
category an instance of some class like Category, that has an array
called article? (If so, I’d suggest making the name plural to show
it’s a collection.)

Which reminds me, watch out for mismatches between human languages.
What you originally wrote wouldn’t work (at least not as intended),
since you’re using “artikel” as your loop variable, and “article”
inside it.

-Dave

On Sat, Oct 13, 2012 at 1:35 PM, Roelof W. [email protected]
wrote:

puts article.name

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

Hello,

Thanks , but I only need 1 of the three category but which one is
chancing.

Roelof

Roelof W. wrote in post #1079718:

You mean a array which contains the array.
That I have

Obviously not. In your original post you had three separate variables:
category1, category2 and category3.

Roelof W. wrote in post #1079718:

but as I said I need one category a time.

Yes, and I showed you how to do it.