khmp":3478hbr1 said:
Now as to the actual "do |iterator(s)|" I'm not exactly sure about wording. To me "do" proceeds an "each" of some kind, and the object inside the || represents a copy of a part of whatever precedes the "each".
The "do" just marks the start of a block. do ... end is the same as { ... }, except that you can use more than one line in a do block. If you want to do that with a curly block you need semi-colons on the end of each line. You can think of blocks as like anonymous functions that get called once for each element in the list/file/whatever.
Incidentally, there are a load of methods that take blocks. Array has a pile of them, not all of them mentioned in the RMXP docs. Want to select all the even numbers from a list?
[1,2,3].select { |i| i % 2 == 0}
That returns a new array. Every element passed to the block in the "i" variable, and if the block evaluates true, it gets copied into the new array. Otherwise it gets left out.
There's a reject version too. I'll do this one with do ... end.
[1,2,3].reject do |i|
i % 2 == 0
end
suppose you have a list of Item IDs and you want a list of item names? Use map:
ids = [2,5,7,14]
names = ids.map { |id| $data_items[id].name }
And each ID in the list gets replaced with the name from the item array
The bit in between the |pipe symbols| is sometimes called a "bound variable". If the block gets called once for each item in an array, then the bound variable is set to item being evaluated for each call. Just like a function argument.
And like a function, you can have more than one parameter: try running each on a Hash, for instance:
h = {"a"=>1, "b"=>2, "c" => 3}
h.each do |k,v|
print "key = #{k}, value = #{v}\n"
end
Hope that helps - it can be a tricky concept to get your head around