Martin Durai wrote:
> Consider the following for loop in 'C' or 'c++' or 'java'
>
> for (i=namespaceEnd - 1; i >= 0; i--)
>
> Please help me with code to do the same functionality in ruby
ruby does not really have a for loop as such but there are various ways
to get the job done. You saw the upto approach. Here is another:
namespaceEnd.times do
# your code in here
end
now, this works for 0..namespace - 1 automatically. If you need to run
in reverse, can use the downto or a calculation.
namespaceEnd.times do |my_var|
some_array[namespaceEnd - my_var] = some_val
end
but that is clunky. If you are iterating through an array you can use
the each loop:
my_arr = ["aaa", "bbb", "ccc", "ddd"]
my_arr.each_with_index {|str, idx| puts "#{idx}. #{str}"}
=>
0. aaa
1. bbb
2. ccc
3. ddd
If you want only the values, use my_arr.each
If you want only the index position, use my_arr.each_index
HTH
--
Posted via
http://www.ruby-forum.com/.