Ruby: Loop

By Xah Lee. Date: . Last updated: .

for-loop

# ruby

# creates a array 1 to 5
aa = 1..5

for xx in aa do p xx; p xx+1 end

# prints 1 to 5

Semicolon can be replaced by newline.

# ruby

# creates a array 1 to 9
aa = 1..9
for xx in aa do
  p xx
end
# prints 1 to 9

Creating a range. Use (1..5).to_a. This creates a array with elements 1 to 5.

# ruby

xx = (1..5).to_a
# to_a converts to array

p xx == [1, 2, 3, 4, 5]
# ruby

p (1..5).class # Range

# methods for the range
p (1..5).methods # [:==, :===, :eql?, :hash, :each, :step, :begin, :end, :first, :last, :min, :max, :to_s, :inspect, :exclude_end?, :member?, :include?, :cover?, :to_a, :entries, :sort, :sort_by, :grep, :count, :find, :detect, :find_index, :find_all, :select, :reject, :collect, :map, :flat_map, :collect_concat, :inject, :reduce, :partition, :group_by, :all?, :any?, :one?, :none?, :minmax, :min_by, :max_by, :minmax_by, :each_with_index, :reverse_each, :each_entry, :each_slice, :each_cons, :each_with_object, :zip, :take, :take_while, :drop, :drop_while, :cycle, :chunk, :slice_before, :nil?, :=~, :!~, :<=>, :class, :singleton_class, :clone, :dup, :initialize_dup, :initialize_clone, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :respond_to_missing?, :extend, :display, :method, :public_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]

Nested for-loop

# ruby

for ii in 1..2 do
  for jj in 1..3 do
    p(ii,jj)
  end
end

# prints 1 1 1 2 1 3 2 1 2 2 2 3
# each on a line

# can also be written in one line
for ii in 1..2 do for jj in 1..3 do p(ii,jj) end end

while-loop

# ruby

x = 1;
while x <= 5 do
  p x
  x += 1
end

Exit Loop

# ruby

for xx in 1..9 do
  p xx
  if xx == 4 then break end
end

# prints 1 to 4

while-loop with break:

# ruby

ii = 1

while ii < 9 do
puts ii;
if ii == 5 then break end
ii += 1
end

# prints 1 to 5