Как установить ruby на windows 10

Вы можете использовать различные инструменты для установки Ruby.
Эта страница описывает, как использовать основные системы управления пакетами
и сторонние инструменты для управления и установки Ruby,
и как собрать Ruby из исходников.

Выберите ваш метод установки

Есть несколько способов установки Ruby:

  • Когда вы на UNIX-подобных операционных системах, использование
    менеджера пакетов вашей системы — это самый простой способ.
    Однако, версия Ruby в пакетных менеджерах не самая последняя.
  • Установщики могут быть использованы для установки конкретной версии или
    нескольких версий Ruby. Есть установщик для Windows.
  • Менеджеры помогут вам переключаться между различными версиями Ruby,
    установленными на вашей системе.
  • Ну и наконец, вы можете также собрать Ruby из исходников.

В следующем списке перечислены доступные способы установки для различных нужд
и платформ.

  • Системы управления пакетами
    • Debian, Ubuntu
    • CentOS, Fedora, RHEL
    • Gentoo
    • Arch Linux
    • macOS
    • OpenBSD
    • Solaris, OpenIndiana
    • Другие дистрибутивы
  • Установщики
    • ruby-build
    • ruby-install
    • RubyInstaller (Windows)
    • Ruby Stack
  • Менеджеры
    • asdf-vm
    • chruby
    • rbenv
    • RVM
    • uru
  • Сборка из исходников

Системы управления пакетами

Если вы не можете скомпилировать ваш собственный Ruby и не хотите
использовать сторонний инструмент для установки – вы можете
воспользоваться пакетным менеджером вашей операционной системы.

Некоторые участники сообщества Ruby убеждены, что никогда не стоит
пользоваться пакетными менеджерами для установки Ruby. Вместо этого
лучше воспользоваться другими инструментами.
Оставим все плюсы и минусы данного подхода за
границами данного текста, отметим лишь, что основной причиной данной
убежденности является то, что в пакетных менеджерах зачастую содержится
информация об устаревших версиях Ruby. Если вы хотите использовать
новейшую версию Ruby, убедитесь, что вы используете верное имя пакета
или воспользуйтесь инструментами описанными ниже вместо этого.

apt (Debian или Ubuntu)

Debian GNU/Linux и Ubuntu используют систему управления пакетами apt.
Вы можете использовать ее следующим образом:

$ sudo apt-get install ruby-full

Пакет ruby-full установит Ruby версии 2.3.1, которая является последним
стабильным релизом.

yum (CentOS, Fedora, или RHEL)

CentOS, Fedora, и RHEL используют систему управления пакетами yum.
Вы можете использовать ее следующим образом:

$ sudo yum install ruby

Устанавливаемая версия обычно является последней версией Ruby, доступной
на момент выхода конкретной версии дистрибутива.

portage (Gentoo)

Gentoo использует систему управления пакетами portage.

$ sudo emerge dev-lang/ruby

По умолчанию, будут установлены версии 1.9 и 2.0, но доступны и другие версии.
Для установки конкретной версии, заполните RUBY_TARGETS в вашем make.conf.
Подробнее смотрите на сайте проекта Gentoo Ruby.

pacman (Arch Linux)

Arch Linux использует систему управления пакетами pacman. Чтобы получить
Ruby, просто напишите следующее:

$ sudo pacman -S ruby

Это должно установить последнюю стабильную версию Ruby.

Homebrew (macOS)

На OS X El Capitan, Yosemite и Mavericks, Ruby 2.0 уже включены.
OS X Mountain Lion, Lion и Snow Leopard поставляются с версией Ruby 1.8.7.

Многие люди на macOS используют Homebrew как пакетный менеджер.
И это действительно просто – установить Ruby:

$ brew install ruby

Это установит последнюю версию Ruby.

OpenBSD

OpenBSD, а также его дистрибутив adJ, имеет пакеты для трех
основных версий Ruby. Следующая команда позволяет вам увидеть
доступные версии и установить одну из них:

$ doas pkg_add ruby

Вы можете установить несколько основных версий одновременно, потому что их
бинарники имеют разные имена (например, ruby27, ruby26).

Ветка HEAD коллекции портов OpenBSD может иметь
самую последнюю версию Ruby для этой платформы через несколько дней после ее
релиза, смотрите
директорию lang/ruby в самой последней коллекции портов.

Ruby на Solaris и OpenIndiana

Ruby 1.8.7 доступен для Solaris 8-10 на Sunfreeware и
Blastwave. Ruby 1.9.2p0 также доступен на Sunfreeware,
но это все уже устарело.

Чтобы установить Ruby на OpenIndiana, пожалуйста, используйте
клиент Image Packaging System, или IPS. Это установит
последние бинарники Ruby и RubyGems прямо из сетевого репозитория
OpenSolaris для Ruby 1.9. Это просто:

$ pkg install runtime/ruby-18

Однако, сторонние инструменты могут быть хорошим способом получить
последнюю версию Ruby.

Другие дистрибутивы

На других системах, вы можете поискать репозиторий пакета Ruby
для пакетного менеджера вашего Linux дистрибутива, или же
сторонние инструменты могут стать хорошим выбором для вас.

Установщики

Если версия Ruby, предоставляемая вашей операционной системой
или пакетным менеджером, не актуальна, то вы можете установить новую версию
при помощи сторонних установщиков. Некоторые из них также позволяют установить
несколько версий Ruby в вашей системе и переключаться между ними. Если вы
планируете использовать RVM как менеджер версий — то вам не нужен
отдельный установщик, он идет со своим.

ruby-build

ruby-build — это плагин для rbenv, который позволяет
вам скомпилировать и установить разные версии Ruby в произвольные каталоги.
ruby-build может использоваться как отдельная программа без rbenv.
Он доступен для macOS, Linux и других UNIX-подобных операционных систем.

ruby-install

ruby-install позволяет вам скомпилировать и установить
различные версии Ruby в произвольные каталоги. Существует также родственник
chruby, который управляет переключением между версиями Ruby.
Он доступен для macOS, Linux и других UNIX-подобных операционных систем.

RubyInstaller

Для пользователей Windows существует отличный проект, помогающий
установить Ruby: RubyInstaller. Он предоставляет вам все,
что нужно для настройки полноценного окружения Ruby на Windows.

Просто скачайте его, запустите и все готово!

Ruby Stack

Если вы устанавливаете Ruby для того, чтобы воспользоваться Ruby on Rails,
вы можете использовать следующий установщик:

  • Bitnami Ruby Stack,
    которые предоставляет полное окружение для разработки на Rails.
    Поддерживает macOS, Linux, Windows, виртуальные машины и облачные сервисы.

Менеджеры

Многие рубисты используют менеджеры для управления несколькими версиями Ruby.
Они предоставляют различные преимущества, но поддерживаются не официально.
Однако их сообщество может оказать помощь.

asdf-vm

asdf-vm — это расширяемый менеджер версий, который может управлять
несколькими исполняемыми версиями языка для каждого проекта. Вам понадобится
плагин asdf-ruby (который, в свою очередь, использует
ruby-build), чтобы установить Ruby.

chruby

chruby позволяет вам переключаться между разными версиями Ruby.
chruby может управлять версиями Ruby, которые установлены с помощью
ruby-install или даже собранными из исходников.

rbenv

rbenv позволяет вам управлять несколькими установленными версиями Ruby.
Он не поддерживает установку Ruby, но для этого существует популярный плагин
ruby-build. Оба инструмента доступны для macOS, Linux и других
UNIX-подобных операционных систем.

RVM (“Ruby Version Manager”)

RVM позволяет вам устанавливать и управлять несколькими установленными
версиями Ruby в вашей системе. Также он может управлять разными наборами гемов.
Доступен для macOS, Linux и других UNIX-подобных операционных систем.

uru

Uru — это легковесная, кросс-платформенная командная утилита, которая
помогает вам использовать несколько версий Ruby на macOS, Linux или Windows.

Сборка из исходников

Конечно, вы можете установить Ruby из исходников.
Скачайте и распакуйте архив, затем просто выполните:

$ ./configure
$ make
$ sudo make install

По умолчанию, это установит Ruby в /usr/local.
Для изменения, передайте опцию --prefix=DIR в скрипт ./configure.

Использование сторонних инструментов или пакетных менеджеров может быть лучше,
хотя бы потому, что установленные Ruby не будут управляться любыми инструментами.

3 августа, 2017 11:41 дп
5 288 views
| Комментариев нет

Ruby

Ruby – это динамический язык программирования, в котором можно написать что угодно: от простых скриптов до игр и веб-приложений. Ruby появился в Японии в 1993 году, но только в 2005 году он стал популярным языком для разработки на стороне сервера. Ruby прост в использовании и с ним легко работать даже новичкам, но он достаточно мощный, чтобы создавать сложные системы. Это отличный выбор для начинающих и опытных разработчиков.

Существует много способов установки Ruby в Windows. Microsoft рекомендует использовать для разработки Ruby Windows Subsystem for Linux (WSL) и Bash. WSL – это функция Windows 10, которая позволяет запускать инструменты командной строки Linux в Windows. Многие библиотеки Ruby предназначены для работы в Linux, и при использовании их в Windows могут возникать проблемы. Компания Microsoft сотрудничает с Linux, чтобы разрешить встроенную поддержку оболочки Bash и инструментов командной строки Linux для решения проблем совместимости Ruby и Windows. Установив Bash и WSL, вы сможете редактировать файлы с помощью инструментов Windows, а для работы Ruby и связанных с ним библиотек использовать Bash.

Данное руководство научит настраивать среду разработки Ruby на локальной машине Windows с помощью командной строки. Для тестирования среды будет создана простая программа Ruby.

Требования

  • Машина Windows 10.
  • Creators Update.
  • Права администратора.

1: Установка Bash в Windows

Для установки Ruby будет использована командная строка. Командная строка представляет собой неграфический способ взаимодействия с компьютером. Вместо нажатия кнопок с помощью мыши вы вводите команды в виде текста и получаете обратную связь опять же в виде текста. Командная строка, также известная как оболочка, позволяет вам автоматизировать многие рутинные задачи и является важным инструментом для разработчиков программного обеспечения.

Windows предлагает два интерфейса командной строки «из коробки»: классическую командную строку и PowerShell. Для работы с Ruby рекомендуется установить строку Bash, популярный командный язык, которые используется в Linux и macOS.

Читайте также: Основы работы с терминалом Linux

Включите на машине Developer mode. Для этого откройте Settings, выберите Update & Security, в боковой панели найдите For developers. Затем выберите опцию Developer mode и подтвердите изменения.

Откройте Control Panel и выберите Programs → Turn Windows features on or off. В списке компонентов выберите опцию Windows Subsystem For Linux (Beta). Кликните OK и подождите, пока система установит дополнительные компоненты. Это может занять несколько минут.

После этого система предложит перезапустить компьютер. Сделайте это, чтобы обновить общесистемные файлы.

После перезагрузки откройте командную строку и введите:

bash

Будет предложено установить Bash из Windows Store. Это бесплатно, загрузка занимает несколько минут.

This will install Ubuntu on Windows, distributed by Canonical
and licensed under its terms available here:
https://aka.ms/uowterms
Press "y" to continue: y
Downloading from the Windows Store... 100%
Extracting filesystem, this will take a few minutes....

После установки инсталлятор предложит создать пользователя:

Please create a default UNIX user account. The username does not need to match your Windows username.
For more information visit: https://aka.ms.wslusers
Enter new UNIX username: 8host
Enter new UNIX password:

Укажите имя пользователя, нажмите Enter, введите пароль.

При вводе пароля символы не отображаются в окне терминала. Эта мера безопасности часто применяется при запросе паролей в командной строке. Вы не будете видеть символов, но система все равно будет фиксировать нажимаемые клавиши. Введите пароль и нажмите Enter, чтобы продолжить.

Оболочка Bash запустится. Командная строка будет выглядеть так:

8host@yourmachine:/mnt/c/Users/8host$

Важно! Windows Subsystem for Linux имеет собственную файловую систему, которая хранится в скрытом файле в операционной системе. Microsoft не поддерживает доступ приложений Windows к этой файловой системе.

Однако все существующие файлы доступны в оболочке Bash. Например, все содержимое диска C можно найти в каталоге /mnt/c. Корпорация Microsoft рекомендует работать с файлами из этой папки. Таким образом, вы можете использовать инструменты Windows для работы с файлами и по-прежнему обращаться к ним из оболочки Bash. Доступ к файлам из других частей Windows Subsystem for Linux через программы Windows, таких как текстовые редакторы, файловые менеджеры и IDE, может привести к повреждению данных и не поддерживается.

2: Установка RVM и Ruby

RVM автоматизирует процесс установки среды Ruby в системе Ubuntu, на которой основана ваша установка Bash.

Самый быстрый способ установить Ruby с помощью RVM – запустить сценарий установки, размещенный на веб-сайте RVM.

Сначала используйте команду gpg, чтобы связаться с сервером открытых ключей и запросить ключ проекта RVM, который используется для подписи каждой версии RVM. Это позволяет подтвердить подлинность релиза RVM. В домашнем каталоге выполните следующую команду:

gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB

Затем установите пакет gnupg2 (сценарий установки RVM будет использовать компоненты этого пакета для проверки релиза). Выполните эту команду:

sudo apt-get install gnupg2

Для установки программы нужно ввести пароль администратора. Однако при вводе пароля символы не отображаются в окне терминала. Эта мера безопасности часто применяется при запросе паролей в командной строке. Вы не будете видеть символов, но система все равно будет фиксировать нажимаемые клавиши. Введите пароль, нажмите Enter и программа будет установлена.

Затем используйте команду curl для загрузки сценария установки RVM с веб-сайта проекта. Обратный слеш в начале команды отключает все псевдонимы команды и запускает обычную команду curl.

\curl -sSL https://get.rvm.io -o rvm.sh

В команде использованы такие флаги:

  • Флаг -s (–silent) отключает индикатор выполнения.
  • Флаг -S (–show-error) включает поддержку сообщений об ошибках curl.
  • Флаг -L (–location) включает обработку редиректов. Если сервер сообщает, что запрошенная страница переместилась на другой адрес, команда автоматически отправит запрос в новое местоположение.

После загрузки можно проверить содержимое сценария перед его запуском:

less rvm.sh

Используйте клавиши со стрелками для прокрутки файла. Чтобы вернуться в командную строку, нажмите q.

Убедившись, что сценарий не содержит ничего лишнего, выполните эту команду, чтобы установить последнюю стабильную версию RVM:

cat rvm.sh | bash -s stable

Сценарий создает в домашнем каталоге новый каталог под названием .rvm. Здесь будет установлен релиз Ruby и все связанные с ним компоненты, а также исполняемая программа rvm, которую вы используете для установки Ruby. Процесс установки изменит файл.bashrc и добавит папку .rvm/bin в переменную среды PATH. Это позволит запускать команду rvm.

Однако в текущей сессии команда rvm будет недоступна. Чтобы исправить это, введите:

source ~/.rvm/scripts/rvm

Используйте rvm, чтобы установить последнюю версию Ruby.

rvm install ruby --default

Эта команда загрузит и установит Ruby и все сопутствующие компоненты и сделает эту версию Ruby версией по умолчанию, чтобы избежать конфликтов, если у вас уже установлена версия другая Ruby.

Searching for binary rubies, this might take some time.
Found remote file https://rvm_io.global.ssl.fastly.net/binaries/ubuntu/16.04/x86_64/ruby-2.4.0.tar.bz2

Если в системе не хватает важных зависимостей, инсталлятор загрузит и установит их. При этом он может запросить пароль пользователя Linux.

Checking requirements for ubuntu.
Installing requirements for ubuntu.
Updating system....
Installing required packages: gawk, libssl-dev, zlib1g-dev, libyaml-dev, libsqlite3-dev, sqlite3, autoconf, libgmp-dev, libgdbm-dev, libncurses5-dev, automake, libtool, bison, libffi-dev, libgmp-dev, libreadline6-dev..................
Requirements installation successful.

Установив зависимости, RVM загрузит и установит Ruby.

ruby-2.4.0 - #configure
ruby-2.4.0 - #download
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
Dload  Upload   Total   Spent    Left  Speed
100 16.4M  100 16.4M    0     0  4828k      0  0:00:03  0:00:03 --:--:-- 4829k
ruby-2.4.0 - #validate archive
ruby-2.4.0 - #extract
ruby-2.4.0 - #validate binary
ruby-2.4.0 - #setup
ruby-2.4.0 - #gemset created /home/brian/.rvm/gems/ruby-2.4.0@global
ruby-2.4.0 - #importing gemset /home/brian/.rvm/gemsets/global.gems..............................
ruby-2.4.0 - #generating global wrappers........
ruby-2.4.0 - #gemset created /home/brian/.rvm/gems/ruby-2.4.0
ruby-2.4.0 - #importing gemsetfile /home/brian/.rvm/gemsets/default.gems evaluated to empty gem list
ruby-2.4.0 - #generating default wrappers........

После выполнения сценария будет установлена последняя версия Ruby.

В дополнение к Ruby RVM устанавливает несколько сопутствующих инструментов: irb (интерактивная консоль Ruby), rake (программа для запуска сценариев автоматизации) и gem (упрощает установку и обновление библиотек Ruby, которые можно использовать в проектах).

Запросите версию Ruby:

ruby -v
ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-linux]

Важно! Чтобы менеджер RVM мог использовать эту версию Ruby при запуске сессий Bash, нужно запустить Bash как login shell. RVM нужен доступ к файлу .bash_profile, который вызывается только в login shell. Bash for Windows не запускает login shell по умолчанию, потому для работы с Ruby нужно открыть командную строку и запустить Bash с помощью команды:

bash -l

Также вместо этого можно запускать следующую команду при каждом запуске Bash:

source ~/.rvm/scripts/rvm

3: Создание простой программы Ruby

Чтобы убедиться, что среда работает, напишите простую программу «Hello, World».

Создайте файл hello.rb:

nano hello.rb

Введите в него следующий код:

puts "Hello, World!"

Нажмите Y, чтобы сохранить файл.

Запустите программу:

ruby hello.rb

Программа выведет на экран следующую фразу:

Hello, World!

Эта простая программа подтверждает, что среда разработки настроена правильно.

Теперь локальная машина готова к разработке программного обеспечения.

Вы можете использовать эту среду для изучения Ruby и создания более сложных и интересных проектов.

Читайте также: Написание простой программы Ruby

Tags: Ruby, RVM, Windows 10

Ruby is a programming language and development environment. It’s often used in web applications, data analysis, and other general-purpose programming.

This guide will show you two options to install Ruby on a Windows 10 system.

tutorial on installing Ruby on Windows 10

Prerequisites

  • A system running Windows 10, updated to version 2004 (May 2020)
  • A user account with administrator privileges
  • Access to the command line / powershell
    (click Start > type “cmd” > right-click > Run as administrator OR Start > type “powershell” >right-click > Run as administrator)

About Ruby: Ruby was developed under the Linux and macOS architecture. There are two ways to run Ruby on Windows. The more straightforward method is to use the Ruby installer to install all the software packages required. The more robust method is to install the Linux subsystem on Windows 10, then use Linux commands to install Ruby.

Installing Ruby Using the RubyInstaller Tool

This process uses the latest version from the Ruby Developer Download page. There are multiple options on this page.

If the system is used for developing software, or you aren’t sure which to choose, use a version With Devkit (Developer’s Kit). If you only need to run Ruby applications, use the version Without Devkit.

Step 1: Download the RubyInstaller Tool

Downloading the Ruby installer tool.r

Use a web browser to navigate to the Download page (linked above). If no specific version is needed, select the bolded option:

Save the file and remember its location.

Step 2: Run the Ruby Installer

1. Browse to the location of the RubyInstaller tool, and double-click.

2. A Setup dialog launches and displays the License Agreement. Review it, tick the box to accept the agreement, then click Next.

installing ruby from install tool

3. The installer asks to adjust the installation location and associated file types. Leave the defaults selected, unless the system requires differently, then click Install.

Set up destination of ruby installation

4. The system prompts to select components. Leave the default settings, and click Next.

Select components for Ruby installation.

5. The Setup dialog runs for several minutes. When finished, it prompts to “Run ‘ridk install’ to setup MSYS2 and development toolchain.” Leave this checked and click Finish.

ruby install is finished

6. A black command-line-style window appears, labeled RubyInstaller2 for Windows. Select the components to install. Press Enter to install the default tools.

Completing Ruby installation for Windows.

7. Once it finishes, press Enter again for the installer to close.

Step 3: Verify the Ruby Installation

If you have any terminal windows open, close them. Open a new terminal window, and enter the following:

ruby –v

The system displays the current version of Ruby installed on Windows 10.

Check Ruby version to verify install

Installing Ruby with the Linux Subsystem

Step 1: Enable the Windows Linux Subsystem (WSL)

Open a command line, and enter the following command:

dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

The system takes a few moments to enable the feature. Then, make sure to reboot the system for the changes to take place.

Enable the Windows Linux subsystem.

Step 2: Install Linux Distro

1. Once the system reboots, launch the Microsoft Store, click Search, and type Linux. The store lists several different versions of Linux that can run within Windows. If you don’t have a preference, Ubuntu 20.04 is a modern, easy-to-use version.

Searching for Linux in Microsoft Store

2. Select the version, then click Get.

3. The store displays that you now own the software. Select Install. You may be prompted to sign in with a Microsoft account. You may skip signing in.

4. Once the process finishes, you can either click Launch or exit the Microsoft Store.

5. Search for the Ubuntu Linux Subsystem in the Start Menu. Open it to complete the installation.

6. Follow the prompts and set up a user account and password for the Ubuntu subsystem. The output then notifies you have successfully installed Ubuntu.

screenshot of Launching Ubuntu subsystem on Windows

Note: The Linux subsystem includes many tools commonly used in Linux. These include the BASH shell, the APT package manager, and others.

Step 3: Update the Linux Subsystem

When using Linux, it’s essential to update the system and software packages before installing new software.

To update your Linux subsystem, open a command line, and enter the following:

sudo apt update

Allow the process to complete. You may be prompted to confirm the installation of some packages – to do so, type y and Enter.

Note: The sudo command stands for SuperUser DO. It lets you run a single command as an administrator, maintaining security on the system while accessing essential tasks.

Step 4: Install Ruby

Once your Linux subsystem is fully installed and updated, install Ruby by entering the following:

sudo apt install ruby-full

Confirm the installation with y and Enter.

Step 5: Verify the Installation

To verify Ruby was successfully installed on Windows 10, enter the following command:

ruby –v

The system should display the current version of the installed Ruby software.

displaying the current Ruby version installed

Conclusion

You should now have the Ruby programming language installed on Windows 10. Next, you may want to look into setting up Ruby on Rails.

Was this article helpful?

YesNo

RUBY

Ruby is a popular language for scripts and web applications. It has been around since the 1990s and is considered a great example of a dynamic, object-oriented programming language. With its elegant syntax and powerful capabilities, Ruby is especially well-known for the Ruby on Rails framework, which simplifies web development. If you’re a developer or an aspiring programmer using Windows 10 and want to install Ruby, you’re in the right place. This guide provides a comprehensive walkthrough on installing Ruby, ensuring you have a solid foundation to build your applications.

Why Use Ruby?

Before diving into the installation process, it’s important to understand why you might choose Ruby for your projects:

  • Simplicity and Productivity: Ruby’s syntax is straightforward, making it easy to read and write.

  • Rich Ecosystem: Ruby has a wealth of libraries (gems) that extend its capabilities.

  • Active Community: The Ruby community is vibrant and offers extensive resources for learning and troubleshooting.

  • Frameworks for Development: Popular frameworks like Ruby on Rails enable rapid development of web applications.

Preparing Your Windows 10 Environment

Before installing Ruby, ensure your Windows 10 environment is ready:

  1. Update Windows: Make sure Windows 10 is updated to the latest version to avoid compatibility issues.

  2. Install a Package Manager: For easy management of Ruby and its dependencies, install a package manager like Chocolatey.

Install Chocolatey

To install Chocolatey, follow these steps:

  1. Open PowerShell as an administrator. You can do this by searching for “PowerShell” in the start menu, right-clicking it, and selecting “Run as Administrator”.

  2. Run the following command to set the execution policy:

   Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
  1. Once the installation completes, close PowerShell.

Installing Ruby Using Chocolatey

With Chocolatey installed, you can now easily install Ruby. Here’s how:

  1. Open a new PowerShell window (not as Administrator).

  2. Run the following command to install Ruby:

  1. Wait for the installation to finish. This process may take a few minutes. Confirm any prompts that appear.

Verify the Installation

To verify that Ruby installed correctly, check the version of Ruby:

  1. Open your Command Prompt by typing cmd in the start menu and hitting enter.

  2. In the Command Prompt window, type:

This command should display the version of Ruby installed, confirming that the installation was successful.

Alternative Installation Methods

While using Chocolatey is one of the simplest ways to install Ruby on Windows, there are other methods available:

Using the RubyInstaller

  1. Download the RubyInstaller from the official RubyInstaller website.

  2. Run the installer and follow the prompts.

  3. During installation, make sure to check the box that adds Ruby to your PATH.

  4. Once installed, open Command Prompt and verify the installation as described previously.

Using Windows Subsystem for Linux (WSL)

If you prefer a UNIX-like environment, consider using Windows Subsystem for Linux (WSL):

  1. Install WSL and a Linux distribution (e.g., Ubuntu) from the Microsoft Store.

  2. Open your WSL terminal and run:

   sudo apt update
   sudo apt install ruby-full
  1. Confirm the installation by checking the Ruby version:

Setting Up Your Development Environment

Now that Ruby is installed, you may want to set up your development environment for scripting or web application development:

Install Bundler

Bundler is a crucial tool for managing Ruby dependencies:

Install Rails (optional)

If you plan to develop web applications with Ruby on Rails:

IDEs and Text Editors

There are several excellent IDEs and text editors you can use for Ruby development:

  • RubyMine: A powerful IDE specifically for Ruby and Rails.

  • Visual Studio Code: A popular text editor with Ruby extensions.

  • Sublime Text: A lightweight text editor that supports Ruby.

Troubleshooting Common Installation Issues

If you encounter issues during installation, consider the following solutions:

  • Compatibility Problems: Ensure that your Windows 10 version is up-to-date.

  • PATH Issues: If Ruby isn’t recognized in the command prompt, check your environment variables to ensure Ruby’s executable path is included.

  • Permission Errors: Make sure PowerShell or Command Prompt is run with administrator privileges when necessary.

Conclusion

Installing Ruby on Windows 10 is a manageable process, whether you use Chocolatey, RubyInstaller, or WSL. Ruby’s flexibility and power can significantly help you in scripting and web application development. With your Ruby environment set up, you can now explore its capabilities and possibly dive into frameworks like Rails to enhance your development skills.

By following the steps outlined in this guide, you are well-equipped to start your journey with Ruby. If you have any questions, don’t hesitate to reach out to the Ruby community for support and resources!

Suggested Articles

RUBY

RUBY

RUBY

RUBY

RUBY

RUBY

Last Updated :
06 Oct, 2021

Prerequisite: Ruby Programming Language

 
Before we start with the installation of Ruby on Windows, we must have first-hand knowledge of what Ruby is?. Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz in the Ruby community) in the mid-1990s in Japan. Everything in Ruby is an object except the blocks but there are replacements too for it i.e procs and lambda. The objective of Ruby’s development was to make it act as a sensible buffer between human programmers and the underlying computing machinery.

 
Ruby is based on many other languages like Perl, Lisp, Smalltalk, Eiffel and Ada. It is an interpreted scripting language which means most of its implementations execute instructions directly and freely, without previously compiling a program into machine-language instructions.

Downloading and Installing Ruby

All the versions of Ruby for Windows can be downloaded from rubyinstaller.org. Download the latest version and follow the further instructions for its Installation.

Ruby-Download-Windows

Beginning with the installation:

Installing MYSYS2 Components:
 

To check if Ruby installed correctly, perform a version check for the same using the following command on the command-line:

ruby -v

Ruby-Windows-Version-Check

Here’s a sample Program to begin with the use of Ruby Programming:
Let’s consider a simple Hello World Program.

 
Using command-line, run the irb command. After this we can write the ruby code and it will run on command line.

Similar Reads

  • Ruby Programming Language

    Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto. Everything in Ruby is an object except the blocks but there are replacements too for it i.e procs and lambda. The objective of Ruby’s develop


    2 min read

  • Overview

    • Ruby For Beginners

      Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro «Matz» Matsumoto in Japan. This article will cover its basic syntax and some basic programs. This article is divided into various sections for various topi


      3 min read


    • Ruby Programming Language (Introduction)

      Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz in the Ruby community) in the mid 1990’s in Japan. Everything in Ruby is an object except the blocks but there are replacements too for it i.e procs and lambda. The objective of Ruby’s development was to make


      4 min read


    • Comparison of Java with Other Programming Languages

      Java is one of the most popular and widely used programming languages and platforms. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable, and secure. From desktop to web applications, scientific supercomputers to gaming cons


      4 min read


    • Similarities and Differences between Ruby and C language

      Similarities between Ruby and C There are many similarities between C and Ruby, and some of them are: Like C, in Ruby also… A programmer is able to program procedurally if they like to do. But still, behind the scenes, it will be object-oriented.Both the languages have the same operators, for exampl


      3 min read


    • Similarities and Differences between Ruby and C++

      There are many similarities between C++ and Ruby, some of them are: Just like C++, in Ruby… As in C++, public, private, and protected works similarly in Ruby also .Inheritance syntax is still only one character, but it’s < instead of : in Ruby.The way ‘namespace’ is used in C++, in the similar wa


      3 min read


    • Environment Setup in Ruby

      Ruby is an interpreted, high-level, general-purpose programming language. Ruby is dynamically typed and uses garbage collection. It supports multiple programming paradigms, object-oriented, including procedural and functional programming. Ruby is based on many other languages like Perl, Lisp, Smallt


      3 min read


    • How to install Ruby on Linux?

      Prerequisite: Ruby Programming Language Before we start with the installation of Ruby on Linux, we must have first-hand knowledge of what Ruby is?. Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz in the Ruby community) in the mid-1990s in Japan. Everything


      2 min read


    • How to install Ruby on Windows?

      Prerequisite: Ruby Programming Language Before we start with the installation of Ruby on Windows, we must have first-hand knowledge of what Ruby is?. Ruby is a pure Object-Oriented language developed by Yukihiro Matsumoto (also known as Matz in the Ruby community) in the mid-1990s in Japan. Everythi


      2 min read


    • Interesting facts about Ruby Programming Language

      Ruby is an interpreted, high-level, dynamic, general-purpose, open source programming language which focuses on simplicity and productivity. It was designed and developed in the mid-1990s by Yukihiro Matsumoto (also known as Matz in the Ruby community) in Japan. Here are some interesting facts about


      2 min read


    Basics

    Control Statements

    Methods

    OOP Concepts

    Exceptions

    Ruby Regex

    Ruby Classes

    Ruby Module

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Проверка срока активации windows
  • Код чтобы активировать windows 10
  • Установка windows 10 на samsung r530
  • Что такое рабочая область windows
  • Hp 4510s drivers windows 10