How To Run Ruby In Vscode

Visual Studio Code, or VSCode, is a popular code editor that supports syntax highlighting, debugging, and code execution for numerous programming languages, including Ruby. In this tutorial, we will show you how to set up and run Ruby code in VSCode.

Prerequisites

Before we begin, make sure you have the following installed on your computer:

  • Ruby: You can check whether you have Ruby installed by running ruby -v in your terminal or command prompt. If you don’t have Ruby installed, you can download it from the official Ruby website.
  • Visual Studio Code: If you don’t have VSCode installed, you can download it from the official Visual Studio Code website.

Step 1: Install the Ruby Extension for VSCode

First, we need to install the Ruby extension in VSCode. This extension provides language support, code formatting, and syntax highlighting for Ruby.

Open Visual Studio Code and click on the Extensions view icon (it looks like a square on the side panel). In the search bar, type “Ruby” and press Enter. Look for the extension named “Ruby” by Peng Lv and click the Install button.

Step 2: Configure the Debugger

Next, we need to set up the debugger for running Ruby code. Click on the Debug view icon (it looks like a bug on the side panel) and click on the gear icon at the top to open the debug configuration file launch.json. If you don’t have any configurations yet, VSCode will create a new file for you.

Add the following configuration to the configurations array in the JSON file:

    {
        "name": "Ruby",
        "type": "Ruby",
        "request": "launch",
        "program": "${workspaceRoot}/main.rb",
        "cwd": "${workspaceRoot}"
    }
    

Save and close the file. This configuration tells the debugger to run the Ruby file named main.rb in the root of your workspace.

Step 3: Create a Ruby File

Create a new file in your workspace’s root directory named main.rb and add some Ruby code. For example:

    def hello_world
        puts 'Hello, World!'
    end

    hello_world
    

Step 4: Run the Ruby Code

Now that everything is set up, we can run the Ruby code. Click on the Debug view icon (the bug icon) and select “Ruby” from the dropdown menu at the top. Click the green play button to start the debugger and run your Ruby code.

The output of the code will appear in the Debug Console, which can be opened by clicking on “View” in the top menu and selecting “Debug Console.”

Conclusion

In this tutorial, we learned how to set up and run Ruby code in Visual Studio Code using the Ruby extension and debugger. This setup allows you to write, debug, and execute your Ruby code all within the same environment, making it a convenient and efficient way to develop Ruby applications.