15 getting technical. I figured an alternative way


#1



https://www.codecademy.com/courses/learn-ruby/lessons/methods-blocks--sorting/exercises/getting-technical


It doesn't behave wrong but I figured out a way thats simpler, but deviates from what the exercise says to do. Basically to sort the books in reverse alphabetical order I just do the following


books.sort!
books.reverse!
puts books

and that works fine, but when I try to go by the example of using a code block like so

books.sort! {|secondbook, firstbook| secondbook <=> firstbook}

it gives me an error asking did you use sort! or sort? what am I doing wrong in the code block.
To be really honest, I am having a bit of an issue with understanding the whole block thing, So can someone recommend a website which explains that in even simpler terms.


#2

I will tell you this, you've flipped the wrong set of firstBook and secondBook
Blocks are ...extremely difficult to grasp at first.

I recommend reading Why's (Poignant) Guide to Ruby

It will help tremendously with understanding what a block is, it's purpose, when to use it, why, what it does etc.

I'll cover some basic syntax here

The curly brace { } begins and ends a block, It's a set of crab pinchers, between them is executable code. Imagine that the first pincer means 'Do' and the last one means 'End'
Normally found after that is | | Those pipes represent Block Arguments. They are variables temporarily held that the block code will be ran against

An example of blockwork

arr = [1,2,3,4,5] an array of the numbers 1 thru 5
arr.each {|| } We see that each has been called and there is a blank block with room for arguments
arr.each{ |i| } We want each number of arr to be held in the block, They no longer have their own identity, prisoners of the block with a cell number of 'i' )(for easy ID, they are integers afterall)

arr.each { |i| puts i * 5} After the Arguments come the code that will be executed against them
So we gave the block our variable arr, told it to call each part of arr |i| and to run it's code against every |i| we gave it.
the block shows us it's work because of our insistence on a puts in the block
5
10
15
20
25
[1,2,3,4,5]
We see the execution of our code then block spits back out our regular arr, unscathed.

More block fun
10.times { puts "blocks are fun" }
You should read this as ' ten times do this code end '

You may still fell confused and overwhelmed by blocks....its totally ok. It takes time, and what matters is that you are putting the time in.
Why's guide is fun, and he's a better teacher than I could hope to be. Check it out

EDIT: ALSO great job figuring out your own way to do it. You'll find especially in Ruby that there are a ton of ways to do the same thing. I caution you don't ever become totally set in your ways in Ruby, variety makes it fun


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.