Difference between For and Map in Ruby -


please let me know difference between these operations. first code works ok:

1) elem in(mr)      elem.shedule = date.new(date.year, date.month, date.day)      end 

but use map:

2) mr.map!{ |elem| elem.shedule = date.new(date.year, date.month, date.day) }   

and second code returns error:

 nomethoderror in events#index  showing c:/sites/calend/app/views/events/_calendar.html.erb line #9 raised:  undefined method `shedule' thu, 04 apr 2013:date  extracted source (around line #9):  6:   </h2> 7:   <%= calendar_for(@repeats, :year => @date.year, :month => @date.month) |calendar| %> 8:     <%= calendar.head('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday') %> 9:     <%= calendar.day(:day_method => :shedule) |date, events| %> 10:       <%= date.day %> <%= link_to '+', new_event_path(date: date) %> 11:       <ul> 12:         <% event in events %> 

you using map in wrong way, should use each instead. code should be:

mr.each |elem|    elem.shedule = date.new(date.year, date.month, date.day) end  

map replaces each element in array value returned block (see linuxios comment below), in example block returns date object. map! performs same operation in place without creating new array, in example mr array of date objects , not of events.

moreover use of for quite uncommon in ruby code, replaced each since:

[1, 2, 3].each |x|   puts x end 

is equivalent (see mladen jablanović comment answer differences) :

for x in [1, 2, 3]   puts x end 

and former considered more "rubyish".


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -