Question on Ruby collect method
I believe your current code cars.collect{|c| c[:company]}
is the best way if you're enumerating over an arbitrary array. The method you would pass in via the & shortcut would have to be a method defined on Hash since each object in the array is of type Hash
. Since there is no company
method defined for Hash
you get the "undefined method 'company'" error.
You could use cars.collect(&:company)
if you were operating on an Array of Cars though, because each object passed into the collect
block would be of type Car
(which has the company method available). So maybe you could modify your code so that you use an array of Cars instead.
what's different between each and collect method in Ruby
Array#each
takes an array and applies the given block over all items. It doesn't affect the array or creates a new object. It is just a way of looping over items. Also it returns self.
arr=[1,2,3,4]
arr.each {|x| puts x*2}
Prints 2,4,6,8 and returns [1,2,3,4] no matter whatArray#collect
is same as Array#map
and it applies the given block of code on all the items and returns the new array. simply put 'Projects each element of a sequence into a new form'
arr.collect {|x| x*2}
Returns [2,4,6,8]And In your code
a = ["L","Z","J"].collect{|x| puts x.succ} #=> M AA K
a is an Array but it is actually an array of Nil's [nil,nil,nil] because puts x.succ
returns nil
(even though it prints M AA K).And
b = ["L","Z","J"].each{|x| puts x.succ} #=> M AA K
also is an Array. But its value is ["L","Z","J"], because it returns self. Ruby - collection of methods
I ended up making an array of procs
What does Integer#times.collect mean?
It is actually a method from Enumerable, a module that is included in Enumerator
.collect
acts as a map
function you give a block to it and the result is saved in an array for every item in your Enumerable
collection.10.times
returns an Enumerble
object with the numbers from 0 to 10 (non-inclusive).
Enumerator: collect method with two parameters
I think you are missing something. This is what you want to do, and it works in both 1.9 and 1.8:
users.collect { |i| { :name => i } }
Difference between map and collect in Ruby?
There's no difference, in fact map
is implemented in C as rb_ary_collect
and enum_collect
(eg. there is a difference between map
on an array and on any other enum, but no difference between map
and collect
).
Why do both
map
and collect
exist in Ruby? The map
function has many naming conventions in different languages. Wikipedia provides an overview:Ruby provides an alias for programmers from the Smalltalk world to feel more at home.The map function originated in functional programming languages but is today supported (or may be defined) in many procedural, object oriented, and multi-paradigm languages as well: In C++'s Standard Template Library, it is called
transform
, in C# (3.0)'s LINQ library, it is provided as an extension method calledSelect
. Map is also a frequently used operation in high level languages such as Perl, Python and Ruby; the operation is calledmap
in all three of these languages. Acollect
alias for map is also provided in Ruby (from Smalltalk) [emphasis mine]. Common Lisp provides a family of map-like functions; the one corresponding to the behavior described here is calledmapcar
(-car indicating access using the CAR operation).
Why is there a different implementation for arrays and enums? An enum is a generalized iteration structure, which means that there is no way in which Ruby can predict what the next element can be (you can define infinite enums, see Prime for an example). Therefore it must call a function to get each successive element (typically this will be the
each
method). Arrays are the most common collection so it is reasonable to optimize their performance. Since Ruby knows a lot about how arrays work it doesn't have to call each
but can only use simple pointer manipulation which is significantly faster.
Similar optimizations exist for a number of Array methods like zip
or count
.
Distinct difference between collect and each?
array = []
is a shortcut to define an array object (long form: array = Array.new
)
Array#collect
(and Array#map
) return a new array based on the code passed in the block. Array#each
performs an operation (defined by the block) on each element of the array.
I would use collect like this:
array = [1, 2, 3]
array2 = array.collect {|val| val + 1}
array.inspect # => "[1, 2, 3]"
array2.inspect # => "[2, 3, 4]"
And each like this:array = [1, 2, 3]
array.each {|val| puts val + 1 }
# >> 2
# >> 3
# >> 4
array.inspect # => "[1, 2, 3]"
Hope this helps... undefined method for collect error
Hey you have trying to call collect
method on your @pages
object on form which is nil
so replace your code in your new action as
def new
@section = Section.new({:name => "Default", :page_id => @page.id})
@section_count = Section.count +1
@pages = @page.subject.pages.sorted
end
now @pages
is not null so you can call collect
method on it. ActiveRecord #collection method is not returning all collection that is saved
When you run "user.posts" first time sql query loads from database all posts with this user. But when you run "user.posts" second time no sql query executed (for performance reasons) so you get only one post. Use "user.posts.reload" to reload posts (new query will be executed)
Related Topics
How to Avoid Circular Creation of Associated Models in Factory_Girl
Loading/Unloading/Updating Class in Ruby
Sinatra on Nginx Configuration - What's Wrong
Why Am I Getting "Unable to Autoload Constant" with Rails and Grape
Functional Testing of a Restful Post in Ruby on Rails
How to Validate This Hash Parameter
Activemodel::Validations on Anonymous Class
How to Handle Omniauth Callbacks in Multiple Environments
How to Properly Manage The Rails Tmp Directory
Posting Ruby Data in JSON Format with Net/Http
Broken Rails Routes After Implementing Single Table Inheritance
Capybara-Webkit: Automatically Save a Screenshot on an Rspec Test Failure
Escaping Strings for Ruby Sqlite Insert
Overriding Instance Variable Array's Operators in Ruby
How to Programmatically Remove "Singleton Information" on an Instance to Make It Marshal