Commit 04020482

040204822b6aMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 8 months ago · 5 files · +1 added · ~4 modified

Description

Add Hash#merge, Hash.new(default), String#dup, Comparable mixin

  • A9: Hash#merge for sp_StrIntHash and sp_RbHash (creates new hash with entries from both, second hash overrides first)
  • A19: sp_String#dup for mutable strings (IntArray#dup and const String#dup already worked)
  • A20: Hash.new(val) with default_value field in sp_StrIntHash; get returns default when key not found
  • B2: attr_writer already handled (verified)
  • B3: Comparable mixin auto-generates <, >, <=, >=, == methods from <=> when class includes Comparable; handles both value and reference type classes

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

Details

Commit
040204822b6a
Parent
f5e8a06c89dd

examples/bm_lrama_features2.rbaddedView file

1+# Test lrama-required features (part 2)
2+
3+# A9: Hash#merge (sp_StrIntHash)
4+h1 = {"a" => 1, "b" => 2}
5+h2 = {"b" => 3, "c" => 4}
6+h3 = h1.merge(h2)
7+puts h3["a"] # 1
8+puts h3["b"] # 3 (h2 overrides h1)
9+puts h3["c"] # 4
10+
11+# A19: Array#dup (already works)
12+arr = [10, 20, 30]
13+arr2 = arr.dup
14+puts arr2[0] # 10
15+puts arr2.length # 3
16+
17+# A19: String#dup (const string)
18+s1 = "hello"
19+s2 = s1.dup
20+puts s2 # hello
21+
22+# A20: Hash.new(0) with default value
23+counter = Hash.new(0)
24+counter["x"] = counter["x"] + 1
25+counter["x"] = counter["x"] + 1
26+counter["y"] = counter["y"] + 1
27+puts counter["x"] # 2
28+puts counter["y"] # 1
29+puts counter["z"] # 0 (default)
30+
31+# B2: attr_writer
32+class Writer
33+ attr_reader :name
34+ attr_writer :name
35+ def initialize(n)
36+ @name = n
37+ end
38+end
39+w = Writer.new("before")
40+puts w.name # before
41+w.name = "after"
42+puts w.name # after
43+
44+# B3: Comparable (include Comparable + def <=>)
45+class Weight
46+ include Comparable
47+ attr_reader :grams
48+ def initialize(g)
49+ @grams = g
50+ end
51+ def <=>(other)
52+ @grams - other.grams
53+ end
54+end
55+
56+w1 = Weight.new(100)
57+w2 = Weight.new(200)
58+w3 = Weight.new(100)
59+puts w1 < w2 # true
60+puts w2 > w1 # true
61+puts w1 == w3 # true
62+puts w1 > w2 # false
63+puts w1 <= w3 # true
64+puts w2 >= w1 # true
65+
66+puts "done"