Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@things.each or 5.times do |t|

Tags:

iteration

ruby

Is there a way to have an iterator that iterates anyways even when the object is nil?

For example, I'd like to strip my views from my application and create a dummy app for a designer.

So I would like it to iterate or loop.

How can this be done?

I've just found a way of doing it

<%
   (@messages.count == 0 ? Array.new(5).map { Message.new } : @messages.each).each do |m|         
%>
like image 876
Joseph Le Brech Avatar asked Feb 21 '12 13:02

Joseph Le Brech


2 Answers

You should be able to use something like this:

(@things || dummy_things).each do |thing|
  # do something with thing
end

def dummy_things
  dummies = []
  5.times do
    dummies.push(Thing.new)
  end
  dummies
end

So what this does is to iterarte over dummy things if @things was nil, otherwise only iterate over @things.

EDIT

A more concise version of dummy_things, as mentioned by Victor, would be something like this:

def dummy_things
  (0..4).map{ Thing.new }
end
like image 165
Behrang Avatar answered Nov 07 '22 22:11

Behrang


Answer is in your question only, even if you don't have any object, you can iterate 5 times using

5.times do |i|
  puts "Dummy page"
end
like image 37
nkm Avatar answered Nov 07 '22 22:11

nkm