I have a few questions for the bubble_sort solution:
In previous lessons, we learned array.each_index. Here we use “each_index” without “array.” in front of it because it is under the Array class and it is common practice to just use “each_index” in this case? Under which circumstances can we use “each_index” alone without an explicit receiver?
Here we have bubble_sort! with and without a proc. In terms of best practice, when should we choose to use/ not use a proc? (When is one better than the other?)
In the screen shots you posted, I see that bubble_sort! is an Array method. This means that self inside of this method is going to represent the array that we call bubble_sort! on.
If I was to run [1,3,2,1].bubble_sort!, the receiver is [1,3,2,1]. If I was to check: self == [1,3,2,1], from inside your method, it will return true. From inside your method, when we are calling each_index, on line 63, we are implicitly calling it on self. So, the receiver of each_index (even though it seems to not have one), is our array ([1,3,2,1]).
I would say that you should be comfortable writing this method both, with and without a proc. I think its a better idea to write bubble_sort accepting a proc, so the method can be used to sort in ascending or descending order. I wouldn’t say that one is better than the other necessarily. I do think that the version of bubble_sort that accepts a proc is the more completed version, and if you know how to code that, you should certainly be able to code the simpler version of it.
Let me know if you still have any questions! Hope this helps!
Thank you for your reply!
According to tutorial, “When a method is called without an explicit self, the implicit self is used, which is the value of the self keyword.” So we can use the implicit self for all methods right?
Self always represents something. If you are at some point not sure what self is, you can use a puts statement to puts self and see what it is in that part of your code to ensure you are using it correctly.
I would say its not a great idea to default to using self implicitly because the more our apps/projects grow the more different variables and method names we have, and that means that we have higher chances of calling another variable or method with the intent of actually calling a method on self. I recommend using the self explicitly until you are very comfortable with the idea of calling methods on self implicitly.
Thank you! That’s good advice.
I just learned more about self in the Classes 2 module. Now I think I understand it.