Learn Enough Ruby to Be Dangerous: Write Programs, Publish Gems, and Develop Sinatra Web Apps with Ruby by Michael Hartl

Learn Enough Ruby to Be Dangerous: Write Programs, Publish Gems, and Develop Sinatra Web Apps with Ruby by Michael Hartl

Author:Michael Hartl [Michael Hartl]
Language: eng
Format: epub, pdf, mobi
Publisher: Addison-Wesley Professional
Published: 2022-06-17T00:00:00+00:00


Click here to view code image

states.reduce({}) { |lengths, state| lengths.merge({state => state.length}) }

See the documentation on merge for more information.)

As required, the result is the same as the imperative solution:

Click here to view code image

$ ruby functional.rb . . . {"Kansas"=>6, "Nebraska"=>8, "North Dakota"=>12, "South Dakota"=>12} {"Kansas"=>6, "Nebraska"=>8, "North Dakota"=>12, "South Dakota"=>12}

Comparing the imperative and functional solutions in Listing 6.9, the advantages of reduce are not as clear as they were in the case of map and select. Indeed, a good argument can be made that the imperative solution is clearer.

Which method to use is a matter of taste. I’ve found that the more you program functionally, the more you want to do it, and there’s a strange sort of pleasure in using reduce to solve a problem in a single (logical) line. It’s also worth noting that reduce is a common technique among more advanced programmers, and among other things plays a key role in an important technique (called MapReduce) for dealing efficiently with large datasets.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.