Automatic counter in Ruby for each?
As people have said, you can use
each_with_index
but if you want indices with an iterator different to "each" (for example, if you want to map with an index or something like that) you can concatenate enumerators with the each_with_index method, or simply use with_index:
blahs.each_with_index.map { |blah, index| something(blah, index)}
blahs.map.with_index { |blah, index| something(blah, index) }
This is something you can do from ruby 1.8.7 and 1.9.
auto increment value in each loop
Easiest way if you don't want to use each_with_index
then You can define variable @count=0
and display, as loop occur it will be increment by 1
<% @count = 0 %>
<% @offers.each do |offer|%>
<%= @count += 1 %> #I guess you want this to show Sr.No
...... # your code
<% end %>
each_with_index way :
<% @offers.each_with_index do |offer, index|%>
<%= index + 1 %> # index starts from 0, so added 1 to start numbering from 1
...... # your code
<% end %>
How To keep track of counter variables in ruby, block, for, each, do
In addition to Ruby 1.8's Array#each_with_index
method, many enumerating methods in Ruby 1.9 return an Enumerator when called without a block; you can then call the with_index
method to have the enumerator also pass along the index:
irb(main):001:0> a = *('a'..'g')
#=> ["a", "b", "c", "d", "e", "f", "g"]
irb(main):002:0> a.map
#=> #<Enumerator:0x28bfbc0>
irb(main):003:0> a.select
#=> #<Enumerator:0x28cfbe0>
irb(main):004:0> a.select.with_index{ |c,i| i%2==0 }
#=> ["a", "c", "e", "g"]
irb(main):005:0> Hash[ a.map.with_index{ |c,i| [c,i] } ]
#=> {"a"=>0, "b"=>1, "c"=>2, "d"=>3, "e"=>4, "f"=>5, "g"=>6}
If you want map.with_index
or select.with_index
(or the like) under Ruby 1.8.x, you can either do this boring-but-fast method:
i = 0
a.select do |c|
result = i%2==0
i += 1
result
end
or you can have more functional fun:
a.zip( (0...a.length).to_a ).select do |c,i|
i%2 == 0
end.map{ |c,i| c }
Is there an alternative to using a counter variable in a each do loop in Ruby?
array = ["a","b","c","a"]
array.each_with_index do |letter,i|
puts "Position: #{i} - Letter: #{letter}"
end
Also, if you will need to have this in map
method, you can use .with_index
modifier:
["a","b","c","a"].map.with_index { |e,i| [e,i] }
=> [["a", 0], ["b", 1], ["c", 2], ["a", 3]]
Finding out current index in EACH loop (Ruby)
X.each_with_index do |item, index|
puts "current_index: #{index}"
end
Using loop counter as part of a variable's name in Ruby
As others have pointed out it is not possible to create local variables dynamically in Ruby, you could set up a binding as well if you're looking for another method of achieving this.
With eval
b = binding
10.times do |i|
eval("var#{i} = 'foo'", b)
end
> eval("var1", b)
=> "foo"
> eval("local_variables", b)
=> [:var9, :var8, :var7, :var6, :var5, :var4, :var3, :var2, :var1, :var0, :b, :_]
Without eval
b = binding
10.times do |i|
b.local_variable_set("var#{i}", 'foo')
end
> b.local_variable_get('var1')
=> "foo"
> b.local_variables
=> [:var9, :var8, :var7, :var6, :var5, :var4, :var3, :var2, :var1, :var0, :b, :_]
Make counter variable in each method increase itself
Just use each_with_index
instead of each
Only caveat: the index starts with 0.
<% @all_posts.each_with_index do |p, a| %>
<%= a %>
<%= p.name %>
<% end %>
See http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-each_with_index
How to increase a simple counter
Let's say you have a Model "Article" with a column "quantity". You could do something in the lines of this (I haven't tested it, just giving you a guideline)
As long as you use the normal resources in your routes:
In your view:
<%= form_for (@article), method: :put do |f| %>
<%= f.button "-", name: "update", value: "decrement" %>
<%= f.button "+", name: "update", value: "increment" %>
<% end %>
In your controller:
def update
@article = Article.find(whatever you use to find it)
if params[:update]["increment"]
@article.quantity += 1
elsif params[:update]["decrement"]
@article.quantity -= 1
end
# repond_to here and so on
# and don't forget to @article.save
end
You could then use jQuery (probably no need for an onClick event) to render the part where you show the count in the view.
auto increment variable in Ruby
A variable is just a name. It doesn't have behavior. If you want behavior, use a method:
def i
@i ||= -1
@i += 1
end
arr = []
arr[i] = 'foo'
arr[i] = 'bar'
arr[i] = 'foobar'
arr #=> ['foo', 'bar', 'foobar']
Alternatively:
_i = -1
define_method(:i) do
_i += 1
end
arr = []
arr[i] = 'foo'
arr[i] = 'bar'
arr[i] = 'foobar'
arr #=> ['foo', 'bar', 'foobar']
But really, what you have is just a very convoluted way of saying
arr = %w[foo bar foobar]
which is much clearer.
Related Topics
Why Can't I Install Rails on Lion Using Rvm
How to Get Request Referer Path
Ruby/Rails - Change the Timezone of a Time, Without Changing the Value
Set Socket Timeout in Ruby Via So_Rcvtimeo Socket Option
Set Utf-8 as Default String Encoding in Heroku
Rails Sends 0 Byte Files Using Send_File
Rubyinstaller 2.2.1 and Rails - Rake Cannot Load Nokogiri
Is the Server Running on Host "Localhost" (::1) and Accepting Tcp/Ip Connections on Port 5432
How to Access Method Arguments in Ruby
Why Not Use Shared Activerecord Connections For Rspec + Selenium
Parallel Assignment Operator in Ruby
Idiomatic Object Creation in Ruby
Why Doesn't My Cron Job Work Properly
Setting Up Rake-Pipeline for Use with Handlebars Alongside Google App Engine