Skip to content

Instantly share code, notes, and snippets.

@vgvinay2
Created July 26, 2017 06:42
Show Gist options
  • Save vgvinay2/9e0134d81c63ed6f9e7c36d3173e1816 to your computer and use it in GitHub Desktop.
Save vgvinay2/9e0134d81c63ed6f9e7c36d3173e1816 to your computer and use it in GitHub Desktop.
Quick sort
def quick_sort(list)
qsort_helper(list).flatten
end
def qsort_helper(list)
return [] if list.empty?
number = list.sample
lower, higher = list.partition { |n| n < number }
higher.delete_at(higher.index(number))
[qsort_helper(lower), number, qsort_helper(higher)]
end
p quick_sort [3, 7, 2, 1, 8, 12]
# [1, 2, 3, 7, 8, 12]
use the sort & the sort_by methods to sort your arrays & hashes in different ways.
hash = {coconut: 200, orange: 50, bacon: 100}
hash.sort_by(&:last)
# [[:orange, 50], [:bacon, 100], [:coconut, 200]]
music = %w(21.mp3 10.mp3 5.mp3 40.mp3)
music.sort
# ["10.mp3", "21.mp3", "40.mp3", "5.mp3"]
music.sort_by { |s| s.scan(/\d+/).first.to_i }
# ["5.mp3", "10.mp3", "21.mp3", "40.mp3"]
Ruby Constant
ABC = 1 correct but if we try
def the_method
ABC = 1
end
Notice that you can’t define constants inside a method.
You will get this cryptic error message:
So just define your constants outside methods, typically we want to have constant definitions at the top of your class so they are clearly visible.
class RubyBlog
URL = "blackbytes.info"
AUTHOR = "Jesus Castello"
end
p RubyBlog::AUTHOR
Ruby constants can change But you will see this warning message
to avoid this AUTHOR = "HEY RUBY".freeze
AUTHOR << "o"
# RuntimeError: can't modify frozen String
nested calss
class A
FOO = 1
end
class A::B
class C
puts FOO
end
end
Notice the A::B notation here, which we tried to use as a shortcut. But the problem is that class C won’t have access to FOO directly.
For that reason you want to stick to this kind of nesting:
class A
FOO = 1
end
class A
class B
class C
puts FOO
end
end
end
In the first example you can still do ::A::FOO to access the constant, but if the class name changes then you will get an error.
This ::A::FOO syntax works because it tells Ruby to look in the top-level scope, where constants like Array & String are defined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment