LoginSignup
16
11
お題は不問!Qiita Engineer Festa 2023で記事投稿!

VS Codeでターミナルからの入力を伴うRubyプログラムをデバッグ実行する方法

Last updated at Posted at 2023-07-08

はじめに

以下のような、ターミナルからの入力を伴うRubyプログラムがあるとします。

print 'input number 1:'
a = gets.to_i
print 'input number 2:'
b = gets.to_i 
puts "answer = #{a + b}"

これをVS Codeの用デバッガ(VSCode rdbg Ruby Debugger)を使ってデバッグ実行する方法を説明します。

実行環境

以下の環境で動作確認しています。

Version: 1.80.0 (Universal)
Commit: 660393deaaa6d1996740ff4880f1bad43768c814
Date: 2023-07-04T13:39:33.766Z
Electron: 22.3.14
ElectronBuildId: 21893604
Chromium: 108.0.5359.215
Node.js: 16.17.1
V8: 10.8.168.25-electron.0
OS: Darwin arm64 22.5.0

デフォルト状態で実行するとダメ🙅‍♂️

以下はデフォルトのlaunch.jsonです。

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "rdbg",
      "name": "Debug current file with rdbg",
      "request": "launch",
      "script": "${file}",
      "args": [],
      "askParameters": true
    },
    {
      "type": "rdbg",
      "name": "Attach with rdbg",
      "request": "attach"
    }
  ]
}

最後の行にブレークポイントを付けます。

Screenshot 2023-07-08 at 20.56.51.png

これでデバッグ実行すると、こうなります。

Screenshot 2023-07-08 at 20.46.58.png

一見、画面下の> 2で入力できているように見えますが、この入力値はgetsメソッドに渡らないため、何をやってもプログラムは2行目から先に進みません😣

useTerminalオプションを指定すればOK👌

そこで、launch.jsonuseTerminalオプション("useTerminal": true)を指定します。

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "rdbg",
      "name": "Debug current file with rdbg",
      "request": "launch",
      "script": "${file}",
      "args": [],
      "askParameters": true,
      "useTerminal": true
    },
    {
      "type": "rdbg",
      "name": "Attach with rdbg",
      "request": "attach"
    }
  ]
}

この状態でデバッグ実行すると、TERMINALタブから値を入力することができます。
(以下は2と3を入力した例。5行目でプログラムが停止している点にも注目)

Screenshot 2023-07-08 at 20.47.50.png

変数の中身を確かめたりしたい場合はDEBUG CONSOLEタブを使います。

Screenshot 2023-07-08 at 20.48.24.png

参考文献

VSCode rdbg Ruby DebuggerのGitHubリポジトリに以下の説明がありました。

- useTerminal
  - If the configuration is true, create a new terminal and then execute the debug command line there. It is a bit slower.
  - Otherwise, all outputs to the STDIN/OUT are shown in the DEBUG CONSOLE.
  - If you need to use STDIN, please set this option.
  - default: false

16
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
11