Commit 96a30f59

96a30f59f7fbMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 8 months ago · 2 files · ~2 modified

Description

Rewrite life.rb with _1, times.map, Range#sum/count blocks

Idiomatic Ruby style using:

  • (-1..1).sum { |iy| (-1..1).count { |ix| ... } } for neighbor counting
  • SIZE.times.map { |i| ... } for grid generation
  • SIZE.times.map { 0 } for initialization
  • cells.count { _1 == 1 } for live cell counting

Also fix: cross-function type inference now traverses block bodies when scanning for nested function calls.

Spinel: <0.01s vs CRuby: 1.49s (>100x faster)

Co-Authored-By: Claude Opus 4.6 (1M context) [email protected]

Details

Commit
96a30f59f7fb
Parent
6387a185907b

examples/life.rbmodifiedView file

@@ -17,50 +17,28 @@
1717 end
1818
1919 def neighbors(cells, x, y)
20- count = 0
21- iy = -1
22- while iy <= 1
23- ix = -1
24- while ix <= 1
25- if cell_get(cells, x + ix, y + iy) == 1
26- count = count + 1
27- end
28- ix = ix + 1
29- end
30- iy = iy + 1
31- end
32- count
20+ (-1..1).sum { |iy|
21+ (-1..1).count { |ix| cell_get(cells, x + ix, y + iy) == 1 }
22+ }
3323 end
3424
3525 def next_gen(cells)
36- new_cells = Array.new
37- y = 0
38- while y < H
39- x = 0
40- while x < W
41- n = neighbors(cells, x, y)
42- alive = cells[y * W + x]
43- if n == 3
44- new_cells.push(1)
45- elsif n == 4 && alive == 1
46- new_cells.push(1)
47- else
48- new_cells.push(0)
49- end
50- x = x + 1
26+ SIZE.times.map { |i|
27+ y = i / W
28+ x = i % W
29+ n = neighbors(cells, x, y)
30+ if n == 3
31+ 1
32+ elsif n == 4 && cells[i] == 1
33+ 1
34+ else
35+ 0
5136 end
52- y = y + 1
53- end
54- new_cells
37+ }
5538 end
5639
5740 # Initialize with a deterministic pattern (glider + blinker)
58-cells = Array.new
59-i = 0
60-while i < SIZE
61- cells.push(0)
62- i = i + 1
63-end
41+cells = SIZE.times.map { 0 }
6442
6543 # Glider at (1,1)
6644 cells[1 * W + 2] = 1
@@ -76,20 +54,11 @@
7654
7755 # Run
7856 gen = 0
79-live = 0
8057 while gen < GENERATIONS
8158 cells = next_gen(cells)
8259 gen = gen + 1
8360 end
8461
8562 # Count final live cells
86-i = 0
87-while i < SIZE
88- if cells[i] == 1
89- live = live + 1
90- end
91- i = i + 1
92-end
93-
94-puts live
63+puts cells.count { _1 == 1 }
9564 puts "done"