There is something I don't understand about ruby.
@items.each do |item|
item.column
end
will work and return me the value for that column in rails. but
item = @items[some_item_id]
item.column
will give me a method not found exception for nil. Both times I get the object but only with the first I can access the rails data methodes.
What do those dashes |...| do and how do I access such methods?
This gathers all elements inside @items
for passage into a block:
@items.each
#each
will work on hashes, arrays, and other enumerables.
This selects a specific element inside @items
:
@items[some_item_id]
The square brackets are a method (named #[]
) for element reference in both hashes and arrays. If you get a MethodNotFound
error, it means @items
is not a hash or array and doesn't have a method named #[]
.
If @items
is a collection of ActiveRecord objects and you want to select one by ID, use:
@items.find(some_item_id)