Lab · Playground
Ruby playground
CRuby 3.4 with its standard library, running as WebAssembly — blocks, Enumerable, pattern matching, and Data classes.
These blocks run CRuby 3.4 itself, compiled to WebAssembly by the
ruby.wasm project, including the standard library. The first
run downloads about 8 MB. Definitions persist between runs on the page, like an irb session;
Stop (or reloading) starts afresh. A block’s final value is shown after ⇒.
Blocks and Enumerable
words = %w[apple banana cherry date elderberry fig grape]
puts words.select { |w| w.length > 4 }.map(&:capitalize).join(", ")
puts words.group_by(&:size).sort.map { |len, ws| "#{len}: #{ws.join(' ')}" }
puts words.each_slice(3).map { |slice| slice.join("+") }.inspect
words.sum(&:length)
Pattern matching and Data classes (Ruby 3.2+)
Point = Data.define(:x, :y) do
def +(other) = with(x: x + other.x, y: y + other.y)
def to_s = "(#{x}, #{y})"
end
def describe(shape)
case shape
in { type: :circle, r: Numeric => r } then "circle, area #{(Math::PI * r**2).round(2)}"
in { type: :rect, w:, h: } if w == h then "square #{w}×#{h}"
in { type: :rect, w:, h: } then "rectangle #{w}×#{h}"
in [Point => a, Point => b] then "segment from #{a} to #{b}"
else "something else"
end
end
puts describe({ type: :circle, r: 2 })
puts describe({ type: :rect, w: 3, h: 3 })
puts describe({ type: :rect, w: 4, h: 2 })
puts describe([Point.new(0, 0), Point.new(1, 2) + Point.new(2, 2)])
The standard library is included
require "json"
require "set"
require "digest"
data = JSON.parse('{"tags": ["wasm", "ruby", "wasm", "browser"], "version": 3.4}')
puts Set.new(data["tags"]).to_a.sort.inspect
puts Digest::SHA256.hexdigest("hello")[0, 16]
puts JSON.pretty_generate({ ruby: RUBY_VERSION, platform: RUBY_PLATFORM })