IronRuby: Ruby on .NET, in your browser
In this lesson your code does not run on CRuby. Every cell goes to IronRuby: a Ruby written in C# that runs on .NET, Microsoft's platform – and this page has .NET itself compiled to WebAssembly and started in a Web Worker, a background thread of the browser. That is about 20 MB to download the first time (the line above shows how far it is); after that the browser has it cached, and IronRuby starts in a few seconds. Only this lesson loads it.
IronRuby began at Microsoft in 2007, on the Dynamic Language Runtime (DLR), the layer that lets dynamic languages like Ruby and Python run on .NET; in 2011 it went quiet. Largo/ironruby is a fork that brought it back: Ruby 4.0 on .NET 8 and 10, parsed by Prism, CRuby's own parser – it is the IronRuby from the list of Rubies in lesson 89. What makes it worth a lesson: from Ruby you can call every .NET library – the whole class library of .NET and any package from NuGet, .NET's RubyGems – and here without installing anything. First, ask it where it is:
puts RUBY_ENGINE, RUBY_VERSION, IRONRUBY_VERSION
info = System::Runtime::InteropServices::RuntimeInformation
[
"your Ruby code",
"IronRuby #{IRONRUBY_VERSION} (written in C#)",
info.FrameworkDescription,
"WebAssembly (#{info.OSDescription})",
"your browser"
].each_with_index { |layer, i| puts "#{' ' * i}#{layer}" }
System::Math.Sqrt(2) # a .NET method, called like a Ruby oneFive layers, one inside the other: your code, IronRuby, .NET, WebAssembly, the browser. RUBY_VERSION is the Ruby language IronRuby speaks, IRONRUBY_VERSION its own release. System::Math is the C# class System.Math: .NET's namespaces and classes are Ruby constants, joined with ::, and Sqrt is called like any Ruby method. info.FrameworkDescription is a C# property – to Ruby, a method without arguments.
Your first QR code
QRCoder is a C# library from NuGet that makes QR codes, 144 KB, and the page has already loaded it. You make its objects with .new, as in Ruby. One thing is different: the values of a C# enum – a fixed list of names, here the error-correction levels L, M, Q and H – are methods in IronRuby, so it is ECCLevel.Q, not ECCLevel::Q. show_png is this lesson's helper; it shows PNG bytes below the cell:
gen = QRCoder::QRCodeGenerator.new
level = QRCoder::QRCodeGenerator::ECCLevel.Q
data = gen.CreateQrCode("Chunky Bacon!", level)
png = QRCoder::PngByteQRCode.new(data).get_graphic(8)
puts "#{png.class}: #{png.length} bytes"
puts "it starts with #{png.to_a.first(4).pack('C*').inspect}"
show_png png
side = data.module_matrix.count
"QR version #{data.version}, #{side} x #{side} modules"Scan it with your phone! It says Chunky Bacon!. The PNG came straight out of .NET: get_graphic returns a System::Byte[], a C# array of bytes – not a Ruby String. to_a turns it into a Ruby Array of numbers, and pack('C*') turns those into a Ruby String of bytes: "\x89PNG", the four bytes every PNG file starts with. Ruby and .NET objects meet in the same program, and IronRuby converts where it can.
Two names, one method
C# names its methods CreateQrCode, Ruby would say create_qr_code. IronRuby offers both: data.Version and data.version, ModuleMatrix and module_matrix are the same. And ECCLevel.send(name) picks an enum value by its name, as send calls any method:
%w[L M Q H].each do |name|
ecc = QRCoder::QRCodeGenerator::ECCLevel.send(name)
d = gen.CreateQrCode("Chunky Bacon!", ecc)
puts "ECC #{ecc}: version #{d.Version}, #{d.ModuleMatrix.Count} modules"
end
puts "the same list: #{data.module_matrix.equal?(data.ModuleMatrix)}"
puts "a #{data.module_matrix.class}"
same = gen.create_qr_code("Chunky Bacon!", level)
puts "create_qr_code: version #{same.version}"More error correction (H) means more modules, so a code still reads with a quarter of it covered. And the last line: create_qr_code works too. IronRuby turns a Ruby name back into a C# one word by word, and it reads a two-letter word as an abbreviation: CreateQRCode. There is no method of that name – so IronRuby looks for the C# method whose Ruby name is create_qr_code, and finds CreateQrCode. A rule of thumb for .NET libraries: the snake_case name almost always works; when one fails, use the C# spelling. That always works.
It is just booleans
module_matrix is a List of BitArrays: one row of true and false per line of the code, true for a dark module. .NET's collections are Enumerable in IronRuby, so each and map work on them as on a Ruby Array – and puts can draw the code:
data.module_matrix.each do |row|
puts row.map { |dark| dark ? "██" : " " }.join
end
nilThat one scans, too. A QR code is nothing more than this grid; the three big squares in the corners tell a camera where it is and which way up. Which means you can draw it yourself – in bacon colours, as an SVG, a picture written as text.
Bacon colours
bacon_svg takes the QR data and two keyword arguments, cell: (how many pixels per module) and plain: (black on white or bacon), both with defaults. %(...) is a string literal like "...", but the double quotes inside it need no backslash – handy for SVG. The two each_with_index go through the .NET list of rows and each row: y is the row, x the column:
def bacon_svg(data, cell: 8, plain: false)
matrix = data.module_matrix
size = matrix.count * cell
dots = []
matrix.each_with_index do |row, y|
row.each_with_index do |dark, x|
next unless dark
hue = 5 + 30 * x / matrix.count # red left, orange right
fill = plain ? "#000" : "hsl(#{hue},75%,32%)"
dots << %(<rect x="#{x * cell}" y="#{y * cell}" width="#{cell}" ) +
%(height="#{cell}" rx="#{plain ? 0 : 2}" fill="#{fill}"/>)
end
end
xmlns = "http://www.w3.org/2000/svg"
paper = plain ? "#fff" : "#fff6e8"
%(<svg xmlns="#{xmlns}" width="#{size}" height="#{size}">) +
%(<rect width="100%" height="100%" fill="#{paper}"/>#{dots.join}</svg>)
end
url = gen.CreateQrCode("https://letsruby.com/", level)
svg = bacon_svg(url)
show_svg svg
"#{svg.scan('<rect').size - 1} dark modules, #{svg.bytesize} bytes of SVG"Red on the left, orange on the right, rounded modules (rx) on cream – and a phone still reads it, because a QR code only needs dark on light. This one leads to this course.
A Swiss QR-bill
Every invoice in Switzerland carries a QR code like the next one: the QR-bill, with the account, the amount and a reference for the payment. QRCoder knows its format. The cell shows more of how C# looks from Ruby: classes inside classes (S::Iban, S::Contact, a constant S to keep the names short), a static factory method that makes an object (WithStructuredAddress), more enums, nil where C# expects null, and System::Decimal, the decimal number C# uses for money – parsed with InvariantCulture, so that "42.50" means the same on every computer, whatever its language:
S = QRCoder::PayloadGenerator::SwissQrCode
iban = S::Iban.new("CH4431999123000889012", S::Iban::IbanType.QrIban)
seller = S::Contact.WithStructuredAddress(
"Chunky Bacon AG", "8000", "Zürich", "CH", "Speckweg", "1"
)
ref = S::Reference.new(S::Reference::ReferenceType.QRR,
"210000000003139471430009017",
S::Reference::ReferenceTextType.QrReference)
info = S::AdditionalInformation.new("Ruby course, IronRuby lesson", nil)
invariant = System::Globalization::CultureInfo.InvariantCulture
amount = System::Decimal.Parse("42.50", invariant) # a C# decimal
bill = S.new(iban, S::Currency.CHF, seller, ref, info, nil, amount)
payload = bill.to_s.to_s # .NET's String, then a Ruby String
puts payload.lines.first(6).map(&:chomp).join(" | ")
# level M and UTF-8 (true), as the standard asks
bill_data = gen.CreateQrCode(payload, bill.ecc_level, true)
# QR-bills are black on white
svg = bacon_svg(bill_data, cell: 5, plain: true)
# the Swiss cross in the middle
c = bill_data.module_matrix.count * 5 / 2.0
box = lambda do |x, y, w, h, fill|
%(<rect x="#{x}" y="#{y}" width="#{w}" height="#{h}" fill="#{fill}"/>)
end
cross = box.(c - 17, c - 17, 34, 34, "#fff") +
box.(c - 15, c - 15, 30, 30, "#000") +
box.(c - 3, c - 10, 6, 20, "#fff") +
box.(c - 10, c - 3, 20, 6, "#fff")
show_svg svg.sub("</svg>", "#{cross}</svg>")
"#{payload.lines.count} lines of payload, QR version #{bill_data.version}"Black on white, with the Swiss cross in the middle: the standard wants it like that, and a banking app reads it only like that (the bacon version did not scan). The standard also asks for error-correction level M, which the bill knows (bill.ecc_level), and for UTF-8, the true, so that "Zürich" arrives with its umlaut. The data inside is plain text – SPC, the version 0200, the account and so on, one field per line. Reading such a code back is what the Ruby gem swiss_qr does.
Operators on a .NET struct
One more piece of .NET: System.Numerics.Complex, the complex numbers of C#. C# can define operators for a type – operator *, operator + – and IronRuby makes them Ruby's * and +; under their C# names (op_Multiply) they are there as well. Ruby has a Complex of its own, so the .NET one gets a constant of its own: NetComplex. Then it draws the Mandelbrot set, the numbers c for which z = z * z + c never grows past 2:
NetComplex = System::Numerics::Complex # Ruby has a Complex of its own
c = NetComplex.new(-0.5, 0.5)
z = NetComplex.new(0, 0)
z = z * z + c # C#'s operator * and operator +
puts z, z.magnitude
puts NetComplex.op_Multiply(c, c) == c * c
# Euler: e to the power of i times pi is -1, up to rounding
puts NetComplex.Exp(NetComplex.ImaginaryOne * Math::PI)
(-12..12).step(2) do |y|
puts((-40..20).map do |x|
c = NetComplex.new(x / 20.0, y / 10.0)
z = NetComplex.new(0, 0)
n = 0
(z = z * z + c; n += 1) while n < 20 && z.magnitude <= 2
n == 20 ? "@" : " .:-=+*#"[n / 3]
end.join)
end
nilputs z shows the number as .NET writes it, <-0.5; 0.5>: puts calls to_s, and for a .NET object that is C#'s ToString.
C# extension methods
A second library: Markdig, Markdown to HTML, 470 KB – the page loads it the first time a cell names it. Markdig adds its features with extension methods: C# methods that a library adds to a class it did not write, here use_advanced_extensions to the MarkdownPipelineBuilder. They count only where you switch them on – with Ruby's own using Markdig, the same using that switches on refinements (using_clr_extensions Markdig, IronRuby's older name for it, does the same). Without that line, use_advanced_extensions is a NoMethodError:
using Markdig
PIPELINE = Markdig::MarkdownPipelineBuilder.new
.use_advanced_extensions
.use_emoji_and_smiley
.build
markdown = <<~MD
# Shopping :pig:
| Thing | Price |
|------|------:|
| Bacon | 4.50 |
| Ruby | 0.00 |
MD
html = Markdig::Markdown.to_html(markdown, PIPELINE)
show_html html
html.to_s.lines.firstIronRuby 4.0 is released for Windows, Linux and macOS, self-contained – no .NET to install. Unpack it and start a Ruby, an iirb or igem, IronRuby's gem:
$ tar xzf ironruby-4.0.5-linux-x64.tar.gz && cd ironruby-4.0.5-linux-x64
$ ./ir.sh -e 'puts RUBY_DESCRIPTION'
$ ./iirb.shA NuGet package is a zip file: take the DLL from its lib/net8.0 folder (or netstandard2.0) and require it with its path, as this page did with QRCoder. On Windows, Windows Forms and WPF are there too: require "System.Windows.Forms", and Ruby opens windows.
qr_svg(text, cell = 6), which returns an <svg> string with one <rect> per dark module – a smaller sibling of bacon_svg, black on white. The cell already makes the QR data and the frame of the SVG; fill rects. The last line shows qr_svg("Chunky Bacon"): scan it, your phone should read Chunky Bacon.def qr_svg(text, cell = 6)
level = QRCoder::QRCodeGenerator::ECCLevel.Q
data = QRCoder::QRCodeGenerator.new.CreateQrCode(text, level)
rects = []
# one <rect x=".." y=".." width=".." height=".."/> per dark module:
# data.module_matrix.each_with_index do |row, y| ... and inside it
# row.each_with_index do |dark, x| ...
size = data.module_matrix.count * cell
%(<svg xmlns="http://www.w3.org/2000/svg" width="#{size}" ) +
%(height="#{size}" style="background:#fff">#{rects.join}</svg>)
end
show_svg qr_svg("Chunky Bacon")