Installing ruby mac os

Installing Ruby

With package managers or third-party tools, you have plenty of options to install and manage Ruby.

You may already have Ruby installed on your computer. You can check inside a terminal emulator by typing:

This should output some information on the installed Ruby version.

Choose Your Installation Method

There are several ways to install Ruby:

  • On a UNIX-like operating system, using your system’s package manager is easiest. However, the packaged Ruby version may not be the newest one.
  • Installers can be used to install a specific or multiple Ruby versions. There is also an installer for Windows.
  • Managers help you to switch between multiple Ruby versions on your system.
  • Finally, you can also build Ruby from source.

On Windows 10, you can also use the Windows Subsystem for Linux to install one of the supported Linux distributions and use any of the installation methods available on that system.

Here are available installation methods:

Package Management Systems

If you cannot compile your own Ruby, and you do not want to use a third-party tool, you can use your system’s package manager to install Ruby.

Some members of the Ruby community feel that you should avoid package managers to install Ruby and that you should use dedicated tools instead.

It is possible that major package managers will install older Ruby versions instead of the latest release. To use the latest Ruby release, check that the package name matches its version number. Or use a dedicated installer.

apt (Debian or Ubuntu)

Debian GNU/Linux and Ubuntu use the apt package manager. You can use it like this:

yum (CentOS, Fedora, or RHEL)

CentOS, Fedora, and RHEL use the yum package manager. You can use it like this:

The installed version is typically the latest version of Ruby available at the release time of the specific distribution version.

snap (Ubuntu or other Linux distributions)

Snap is a package manager developed by Canonical. It is available out-of-the-box on Ubuntu, but snap also works on many other Linux distributions. You can use it like this:

We have several channels per Ruby minor series. For instance, the following commands switch to Ruby 2.3:

portage (Gentoo)

Gentoo uses the portage package manager.

To install a specific version, set RUBY_TARGETS in your make.conf . See the Gentoo Ruby Project website for details.

pacman (Arch Linux)

Arch Linux uses a package manager named pacman. To get Ruby, just do this:

This should install the latest stable Ruby version.

Homebrew (macOS)

Ruby versions 2.0 and above are included by default in macOS releases since at least El Capitan (10.11).

Homebrew is a commonly used package manager on macOS. Installing Ruby using Homebrew is easy:

This should install the latest Ruby version.

FreeBSD

FreeBSD offers both pre-packaged and source-based methods to install Ruby. Prebuilt packages can be installed via the pkg tool:

Читайте также:  Linux скопировать имена файлов

A source-based method can be used to install Ruby using the Ports Collection. This is useful if you want to customize the build configuration options.

More information about Ruby and its surrounding ecosystem on FreeBSD can be found on the FreeBSD Ruby Project website.

OpenBSD

OpenBSD as well as its distribution adJ has packages for the three major versions of Ruby. The following command allows you to see the available versions and to install one:

You can install multiple major versions side by side, because their binaries have different names (e.g. ruby27 , ruby26 ).

The HEAD branch of the OpenBSD ports collection might have the most recent version of Ruby for this platform some days after it is released, see directory lang/ruby in the most recent ports collection.

Ruby on OpenIndiana

To install Ruby on OpenIndiana, please use the Image Packaging System (IPS) client. This will install the Ruby binaries and RubyGems directly from the OpenIndiana repositories. It’s easy:

However, the third-party tools might be a good way to obtain the latest version of Ruby.

Windows Package Manager

On Windows, you can use the Windows Package Manager CLI to install Ruby:

Other Distributions

On other systems, you can search the package repository of your Linux distribution’s manager for Ruby. Alternatively, you can use a third-party installer.

Installers

If the version of Ruby provided by your system or package manager is out of date, a newer one can be installed using a third-party installer.

Some installers allow you to install multiple versions on the same system; associated managers can help to switch between the different Rubies.

If you are planning to use RVM as a version manager you don’t need a separate installer, it comes with its own.

ruby-build

ruby-build is a plugin for rbenv that allows you to compile and install different versions of Ruby. ruby-build can also be used as a standalone program without rbenv. It is available for macOS, Linux, and other UNIX-like operating systems.

ruby-install

ruby-install allows you to compile and install different versions of Ruby into arbitrary directories. chruby is a complimentary tool used to switch between Ruby versions. It is available for macOS, Linux, and other UNIX-like operating systems.

RubyInstaller

On Windows, RubyInstaller gives you everything you need to set up a full Ruby development environment.

Just download it, run it, and you are done!

Ruby Stack

If you are installing Ruby in order to use Ruby on Rails, you can use the following installer:

  • Bitnami Ruby Stack provides a complete development environment for Rails. It supports macOS, Linux, Windows, virtual machines, and cloud images.

Managers

Many Rubyists use Ruby managers to manage multiple Rubies. They allow easy or even automatic switching between Ruby versions depending on the project and other advantages but are not officially supported. You can however find support within their respective communities.

asdf-vm

asdf-vm is an extendable version manager that can manage multiple language runtime versions on a per-project basis. You will need the asdf-ruby plugin (which in turn uses ruby-build) to install Ruby.

chruby

chruby allows you to switch between multiple Rubies. It can manage Rubies installed by ruby-install or even built from source.

rbenv

rbenv allows you to manage multiple installations of Ruby. While it can’t install Ruby by default, its ruby-build plugin can. Both tools are available for macOS, Linux, or other UNIX-like operating systems.

Читайте также:  Как узнать почему компьютер сам перезагружается windows 10

RVM (“Ruby Version Manager”)

RVM allows you to install and manage multiple installations of Ruby on your system. It can also manage different gemsets. It is available for macOS, Linux, or other UNIX-like operating systems.

Uru is a lightweight, multi-platform command line tool that helps you to use multiple Rubies on macOS, Linux, or Windows systems.

Building from Source

Of course, you can install Ruby from source. Download and unpack a tarball, then just do this:

By default, this will install Ruby into /usr/local . To change, pass the —prefix=DIR option to the ./configure script.

You can find more information about building from source in the Ruby README file.

Using the third-party tools or package managers might be a better idea, though, because the installed Ruby won’t be managed by any tools.

Источник

Установка Ruby и настройка локальной среды разработки в macOS

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

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

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

Требования

  • Локальная машина macOS (El Capitan и выше).
  • Права администратора.
  • Подключение к интернету.

1: Терминал macOS

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

Открыть приложение терминала в macOS можно через Finder → Applications → Utilities. Здесь дважды кликните по приложению Terminal.

Также для доступа к терминалу можно зажать Command, нажать Space и ввести Terminal в появившемся поле.

2: Установка инструментов командной строки Xcode

Xcode – это интегрированная среда разработки (IDE), которая включает инструменты разработки программного обеспечения для macOS. Для записи Ruby-программ Xcode не понадобится, но Ruby и некоторые его компоненты зависят от пакета Xcode.

Введите в терминал:

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

Теперь можно установить менеджер пакетов Homebrew, который поможет установить последнюю версию Ruby.

3: Установка и настройка Homebrew

Интерфейс командной строки macOS обладает почти всеми функциями Linux и других Unix- подобных систем, но он не включает в себя менеджер пакетов. Менеджер пакетов – это набор инструментов, который автоматизирует установку, настройку и обновление программ. Эти инструменты обеспечивают централизованное хранение программ и могут поддерживать все программные пакеты в системе в разных форматах. Homebrew – это бесплатная система управления пакетами с открытым исходным кодом, которая упрощает установку программного обеспечения на macOS. Используйте Homebrew, чтобы установить последнюю версию Ruby, а затем настроить систему для использования этой версии вместо текущей версии Ruby по умолчанию.

Читайте также:  Общие сведения windows live onecare

Чтобы установить Homebrew, введите в терминал:

/usr/bin/ruby -e «$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)»

Homebrew и его сценарий установки написаны на Ruby, для его установки можно использовать интерпретатор Ruby, который поставляется с macOS по умолчанию. Команда использует curl для загрузки сценария установки Homebrew из репозитория Git на GitHub.

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

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

После загрузки сценарий выполняется интерпретатором Ruby.

Сценарий установки опишет свои действия и предложит подтвердить их. Так вы будете точно знать, что Homebrew собирается сделать в системе, и заранее установить зависимости.

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

Если система запросит подтверждения, нажмите y.

После установки нужно сделать каталог, который Homebrew использует для хранения исполняемых файлов, первым значением переменной среды PATH. Так все инструменты macOS смогут вызывать установленные через Homebrew программы. К примеру, после установки Ruby с помощью Homebrew система сможет запустить эту версию.

Добавьте в конец файла:

Чтобы сохранить изменения, удерживайте клавишу Ctrl и O, при появлении запроса нажмите клавишу Return. Затем выйдите из редактора, удерживая клавишу Ctrl и нажав X. Это вернет вас в терминал.

Чтобы активировать все изменения, введите:

После этого изменения, внесенные в переменную среды PATH, вступят в силу.

Убедитесь, что Homebrew работает. Введите:

В терминале появится:

Your system is ready to brew.

Если что-то пошло не так, вы можете получить предупреждение. Если Homebrew нужно обновить, вам будет предложено ввести команду:

4: Установка Ruby

После установки Homebrew вы можете легко установить множество инструментов разработки и других программ. Давайте установим Ruby и зависимости.

Следующая команда выводит список всех доступных пакетов Homebrew:

Чтобы сузить поиск пакета, укажите его имя, например:

brew search ruby
chruby
chruby-fish
imessage-ruby
jruby
mruby
rbenv-bundler-ruby-version
ruby
ruby-build
ruby-completion
ruby-install
ruby@1.8
ruby@1.9
ruby@2.0
ruby@2.1
ruby@2.2
ruby@2.3
homebrew/portable/portable-ruby
homebrew/portable/portable-ruby@2.2

Найдите в списке Ruby и установите этот пакет:

brew install ruby

В терминале вы увидите аналогичный вывод. Сначала Homebrew установит множество зависимостей, а затем загрузит и установит Ruby:

==> Installing dependencies for ruby: readline, libyaml, openssl
.
==> Summary
/usr/local/Cellar/ruby/2.4.1_1: 1,191 files, 15.5MB

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

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

Команда вернет новую версию Ruby:

ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-darwin15]

Чтобы обновить версию Ruby, сначала обновите Homebrew, а затем Ruby:

brew update
brew upgrade ruby

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

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

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

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

puts «Hello, World!»

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

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

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

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

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

Источник

Оцените статью