@ledsun blog

無味の味は佳境に入らざればすなわち知れず

RubyスクリプトをWebAssembly化したRubyランタイムで動かす

wordleの候補をgrepするRubyスクリプト - @ledsun blogをブラウザで動くようにしたいと思います。

ruby.wasm/lucky.html at main · ruby/ruby.wasm · GitHub を参考にして実装していきます。

<html>
  <script src="https://cdn.jsdelivr.net/npm/ruby-head-wasm-wasi@0.3.0-2022-09-06-f/dist/browser.script.iife.js"></script>
  <script type="text/ruby">
    require "js"

    dict = %w[
    abaci
    aback
    abaft
        ]

    def search dict, exclude, included, correct_spots
      matched = dict.grep(/^#{correct_spots}$/)
                    .grep_v(/[#{exclude}]/)

      included.to_s.chars.each do |char|
        matched = matched.grep(/#{char}/)
      end
      matched
    end

    document = JS.global[:document]
    search_button = document.getElementById "search_button"
    search_button.addEventListener "click" do
      exclude = document.getElementById("exclude")[:value]
      included = document.getElementById("included")[:value]
      correct_places = document.getElementById("correct_places")[:value]
      matched = search dict, exclude, included, correct_places
      
      html = matched.map do |m|
        "<div>#{m}</div>"
      end.join
      document.getElementById("result")[:innerHTML] = html
    end

  </script>
  <div>
    exclude: <input type="text" id="exclude">
  </div>
  <div>
    included: <input type="text" id="included">
  </div>
  <div>
    corrct_places: <input type="text" id="correct_places" value="\w\w\w\w\w">
  </div>
  <div>
    <button type="button" id="search_button">Search</button>
  </div>
  <div id="result"></div>

</html>

辞書データははしょってあります。 次のコマンドでHTTPサーバーを起動します。

ruby -run -e httpd

ブラウザで実行すると次のような検索が出来ます。

ブラウザで実行した結果

つまづいた点

TODO

  • 結果表示を等幅フォントにする
  • 結果表示に色付けする
  • GitHub page辺りに配置してインターネットからアクセスできるようにする