Skip to content

Commit 23ecdcf

Browse files
Nic Hartleyjiegillet
Nic Hartley
authored andcommitted
Making the Ruby bogosort more idiomatic (#437)
* Idiomatized is that even a word? * More idiomaticity I don't think that's a real word, either * Update bogo_sort.md
1 parent b543263 commit 23ecdcf

File tree

2 files changed

+10
-22
lines changed

2 files changed

+10
-22
lines changed

contents/bogo_sort/bogo_sort.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ In code, it looks something like this:
4444
{% sample lang="nim" %}
4545
[import:16-18, lang:"nim"](code/nim/bogo_sort.nim)
4646
{% sample lang="ruby" %}
47-
[import:12-16, lang:"ruby"](code/ruby/bogo.rb)
47+
[import:7-9, lang:"ruby"](code/ruby/bogo.rb)
4848
{% endmethod %}
4949

5050
That's it.

contents/bogo_sort/code/ruby/bogo.rb

Lines changed: 9 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,19 @@
11
#!/usr/bin/env ruby
22

33
def is_sorted(a)
4-
for i in 0...a.length-1
5-
if a[i+1] < a[i]
6-
return false
7-
end
8-
end
9-
return true
4+
a.each_cons(2).all? { |(l, r)| l <= r }
105
end
116

127
def bogo_sort(a)
13-
while !is_sorted(a)
14-
a.shuffle!
15-
end
8+
a.shuffle! until is_sorted a
169
end
1710

18-
def main()
19-
a = [1, 1, 0, 3, 7]
20-
21-
puts("Unsorted")
22-
print(a)
23-
24-
bogo_sort(a)
25-
26-
puts("\n\nSorted")
27-
print(a)
28-
end
11+
a = [1, 1, 0, 3, 7]
12+
13+
puts "Unsorted"
14+
p a
2915

30-
main()
16+
bogo_sort a
3117

18+
puts "Sorted"
19+
p a

0 commit comments

Comments
 (0)