Как обновить ruby
Перейти к содержимому

Как обновить ruby

  • автор:

How can I update Ruby version 2.0.0 to the latest version in Mac OS X v10.10 (Yosemite)?

I need to update my Ruby version from 2.0.0 to the latest version. I can not use some gems because my version is not updated. I had used Homebrew to install Ruby some time ago. How can I update my Ruby version?

30.8k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
asked Jul 5, 2016 at 1:33
4,933 3 3 gold badges 10 10 silver badges 6 6 bronze badges
what happens when you type which rvm or which rbenv in your command line
Jul 5, 2016 at 1:36
@ChuchaC Please, take a look here and here
Jul 5, 2016 at 1:44
looks like brew install ruby is enough. check here
Oct 27, 2018 at 6:04

15 Answers 15

Open your terminal and run

curl -sSL https://raw.githubusercontent.com/rvm/rvm/master/binscripts/rvm-installer | bash -s stable 

For the rvm command to work, you need to run:

source ~/.rvm/scripts/rvm 

Now, run rvm list known

This shows the list of versions of the Ruby interpreter.

Now, run rvm install ruby@latest to get the latest Ruby version.

If you type ruby -v in the terminal, you should see ruby X.X.X .

If it still shows you ruby 2.0. , run rvm use ruby-X.X.X —default .

Prerequisites for Windows 10:

  • C compiler. You can use http://www.mingw.org/
  • make command available otherwise it will complain that «bash: make: command not found». You can install it by running mingw-get install msys-make
  • Add «C:\MinGW\msys\1.0\bin» and «C:\MinGW\bin» to your path environment variable

1,867 2 2 gold badges 25 25 silver badges 42 42 bronze badges
answered Jul 5, 2016 at 1:51
Abhinay Reddy Keesara Abhinay Reddy Keesara
9,773 2 2 gold badges 18 18 silver badges 28 28 bronze badges
2.2.0 is not the latest version of Ruby.
Jul 5, 2016 at 2:04
@Jordan My bad 2.3 is the stable version
Jul 5, 2016 at 2:09
This works on Mac OS to install RVM: \curl -sSL https://get.rvm.io | bash -s stable —ruby
Dec 28, 2016 at 16:04
2.4 is the latest stable version: rvm install ruby-2.4.0
Jan 27, 2017 at 13:41
piping curl output straight to execution is a security nightmare waiting to happen.
Jan 8, 2018 at 11:54

Brew only solution

A better solution

From the comments (kudos to Maksim Luzik), I haven’t tested but seems like a more elegant solution:

After installing Ruby through brew, run the following command to update the links to the latest Ruby installation: brew link —overwrite ruby

A solution

Using brew is enough. It’s not necessary to install rvm and for me it just complicated things.

By brew install ruby you’re actually installing the latest (currently v2.4.0). However, your path finds 2.0.0 first. To avoid this just change precedence (source). I did this by changing ~/.profile and setting:

After this, I found that the bundler gem was still using version 2.0.0. Just install it again: gem install bundler

30.8k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
answered Feb 16, 2017 at 23:22
Sergio Basurco Sergio Basurco
3,538 2 2 gold badges 22 22 silver badges 40 40 bronze badges

Exactly what I was looking for, thanks. If I was a ruby dev then rvm would make sense, but I’m not, so this is perfect.

Jun 23, 2017 at 3:17
this works, needed to do «source ~/.bash_profile» after install
Aug 15, 2017 at 18:51

or after installing ruby through brew, run following command to update the links to the latest ruby installation: brew link —overwrite ruby

Aug 31, 2017 at 14:41
instead of overwrite ruby version, you can just write brew unlink ruby && brew link ruby
Nov 2, 2017 at 15:25

@MaksimLuzik ‘s solution does not work for me in MacOS. brew link —overwrite ruby leads to Warning: Refusing to link macOS-provided software: ruby

Jul 3, 2019 at 7:42

rbenv does…

  • Provide support for specifying application-specific Ruby versions.
  • Let you change the global Ruby version on a per-user basis.
  • Allow you to override the Ruby version with an environment variable.

In contrast with RVM, rbenv does not…

  • Need to be loaded into your shell. Instead, rbenv’s shim approach works by adding a directory to your $PATH .
  • Override shell commands like cd or require prompt hacks. That’s dangerous and error-prone.
  • Have a configuration file. There’s nothing to configure except which version of Ruby you want to use.
  • Install Ruby. You can build and install Ruby yourself, or use ruby-build to automate the process.
  • Manage gemsets.Bundler is a better way to manage application dependencies. If you have projects that are not yet using Bundler you can install the rbenv-gemset plugin.
  • Require changes to Ruby libraries for compatibility. The simplicity of rbenv means as long as it’s in your $PATH , nothingelse needs to know about it.

INSTALLATION

Install Homebrew http://brew.sh

$ brew update $ brew install rbenv ruby-build # Add rbenv to bash so that it loads every time you open a terminal echo 'if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi' >> ~/.bash_profile source ~/.bash_profile
$ rbenv install --list Available versions: 1.8.5-p113 1.8.5-p114 […] 2.3.1 2.4.0-dev jruby-1.5.6 […] $ rbenv install 2.3.1 […]

Set the global version:

$ rbenv global 2.3.1 $ ruby -v ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]

If you are not showing the updated version then

$ rbenv rehash

Set the local version of your repository by adding .ruby-version to your repository’s root directory:

$ cd ~/whatevs/projects/new_repo $ echo "2.3.1" > .ruby-version

For OS X, visit this link.

2,435 2 2 gold badges 25 25 silver badges 34 34 bronze badges
answered Jul 5, 2016 at 2:06
SoAwesomeMan SoAwesomeMan
3,216 1 1 gold badge 22 22 silver badges 25 25 bronze badges

@ChuchaC No prob. But before you do, this is from the rbenv readme: «Compatibility note: rbenv is incompatible with RVM. Please make sure to fully uninstall RVM and remove any references to it from your shell initialization files before installing rbenv.» — github.com/rbenv/rbenv#installation

Jul 6, 2016 at 2:33
didn’t helped. Still getting standard 2.0.0 version for ruby -v after rbenv global .
Sep 8, 2016 at 10:57

There’s one additional step after brew install rbenv Run rbenv init and add one line to .bash_profile as it states. After that reopen your terminal window, do rbenv install 2.3.1 , rbenv global 2.3.1 and rbenv will do its work

Sep 30, 2016 at 12:01

Probably late but for future references for people who encountered the same issue as @tuxSlayer , rbenv rehash after rbenv global worked for me

Feb 1, 2017 at 3:01

After rbenv init , ruby -v outputs the correct version 2.1.2, but bundle runs encounters some error like this paperclip-5.0.0.beta1 requires ruby version >= 2.1.0, which is incompatible with the current version, ruby 2.0.0p648 . Finally manage to get it work with a run of rbenv rehash . Thanks @Sean

Apr 14, 2017 at 3:43

sudo gem update --system 

36.3k 27 27 gold badges 84 84 silver badges 93 93 bronze badges
answered Nov 4, 2016 at 14:51
Cristian Guaman Cristian Guaman
1,027 7 7 silver badges 5 5 bronze badges

This does indeed seem to work, and is a unmeasurably more straight forward than the other answers. But when installing some gems (listen for example) they complain that the version is lower than required.

Nov 9, 2016 at 9:38
This is gem not ruby
Feb 17, 2017 at 2:32
Brew only solution here
Jun 21, 2017 at 8:02

I was misled by this answer too. It «works» in that no errors are generated when you run it from the console. However, it does not update Ruby. It updates Ruby Gems. Follow one of the other answers to update Ruby (using OS X Sierra).

Aug 14, 2017 at 19:40

Tried it, but i got the following error: ERROR: Error installing rubygems-update: rubygems-update requires Ruby version >= 2.3.0. ERROR: While executing gem . (NoMethodError) undefined method `version’ for nil:NilClass

Jul 20, 2020 at 13:26

A fast way to upgrade Ruby to v2.4+

brew upgrade ruby 
sudo gem update --system 

30.8k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
answered Jun 9, 2017 at 13:30
fatihyildizhan fatihyildizhan
8,684 7 7 gold badges 64 64 silver badges 88 88 bronze badges

This appears to do a ton of stuff, but upgrading ruby isn’t one of them. It terminates with: /usr/local/Homebrew/Library/Homebrew/brew.rb:12:in ‘

‘: Homebrew must be run under Ruby 2.3! You’re running 2.0.0. (RuntimeError)

Jan 5, 2018 at 16:06
This is the correct and best way to upgrade ruby version using brew.
Apr 23, 2018 at 20:12

Doesn’t work for me. ERROR: While executing gem . (Errno::EPERM) Operation not permitted @ rb_sysopen — /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/bin/gem

Mar 20, 2020 at 10:14
@SébastienLoisel can you please give some detail about your OS, command etc.
Mar 20, 2020 at 10:15

@fatihyildizhan apparently ruby/gems/etc is in a semibroken state on Mavericks. I’ve resolved my issues by upgrading to Catalina. I don’t remember all the errors I had, but there were multitudes. I can’t remember if I was trying to upgrade cocoapods or gems or what, but it was essentially hopeless.

Mar 21, 2020 at 14:05

You can specify the latest version of Ruby by looking at Download Ruby.

    Fetch the latest version:

curl -sSL https://get.rvm.io | bash -s stable --ruby 
rvm install 2.2 
rvm use 2.2 --default 

Or run the latest command from ruby:

rvm install ruby --latest rvm use 2.2 --default 

30.8k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
answered Dec 13, 2016 at 12:40
julien bouteloup julien bouteloup
3,022 22 22 silver badges 16 16 bronze badges
Thanks, this worked for me. Solution with rbenv wasn’t working
Mar 15, 2017 at 21:04
This worked for me too!! The solution with rbenv did NOT work
Dec 3, 2017 at 3:07
On Mac I had to do source ~/.bash_profile to use rvm
Mar 6 at 23:14

brew install rbenv ruby-build

Add rbenv to Bash so that it loads every time you open a terminal:

echo ‘if which rbenv > /dev/null; then eval «$(rbenv init -)»; fi’ >> ~/.bash_profile

Install Ruby

rbenv install 2.6.5

rbenv global 2.6.5

30.8k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
answered Dec 2, 2019 at 5:38
Mohanraj Karatadipalayam Mohanraj Karatadipalayam
589 4 4 silver badges 10 10 bronze badges
This «rbenv» may refer to SoAwesomeMan’s answer.
Apr 12 at 18:55

In case of the error “Requirements installation failed with status: 1.”, here’s what to do:

Install Homebrew (for some reason it might not work automatically) with this command:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 

Then proceed to install rvm again using

curl -sSL https://get.rvm.io | bash -s stable --ruby 

Quit, reopen Terminal, and then:

rvm install 2.2 rvm use 2.2 --default 

30.8k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
answered Mar 3, 2017 at 19:51
Paula Hasstenteufel Paula Hasstenteufel
720 8 8 silver badges 18 18 bronze badges

✅ Working 2023 method:

Upgrade using the homebrew:

brew upgrade ruby echo 'export PATH="/opt/homebrew/opt/ruby/bin:$PATH"' >> ~/.zshrc brew link --overwrite ruby 

Then restart the Terminal (make sure you terminate all instances, quit and open again)

Then ruby -v to check if it linked correctly.

��Recommended Followup:

It’s not required but you can run the following after upgrading the ruby to update gem files:

gem update --system 3.4.2 

⚠️ The above version may be changed when you have upgraded your ruby. Please use the correct version as reported after the installation of the ruby.

answered Oct 9 at 7:49
Mojtaba Hosseini Mojtaba Hosseini
97.8k 32 32 gold badges 279 279 silver badges 282 282 bronze badges

In terminal : rvm gemset use global

answered Apr 13, 2017 at 12:39
9 1 1 bronze badge

While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

Apr 13, 2017 at 15:21

I ended up using the steps below due to React Native 0.70 and macOS v12 (Monterey).

brew install ruby 
open -e ~/.zshrc 

Set the $PATH environment variable. Add this at the end of your ~/.zshrc file. On Mac Intel:

if [ -d "/usr/local/opt/ruby/bin" ]; then export PATH=/usr/local/opt/ruby/bin:$PATH export PATH=`gem environment gemdir`/bin:$PATH eval "$(rbenv init -)" fi 
if [ -d "/opt/homebrew/opt/ruby/bin" ]; then export PATH=/opt/homebrew/opt/ruby/bin:$PATH export PATH=`gem environment gemdir`/bin:$PATH eval "$(rbenv init -)" fi 

Don’t want brew to update your version?

brew pin ruby 

30.8k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
answered Dec 27, 2022 at 14:48
Alex Nolasco Alex Nolasco
18.8k 9 9 gold badges 87 87 silver badges 81 81 bronze badges

sudo gem update --system 

And simply restart the PC.

30.8k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
answered Jan 13 at 10:31
Kiran Chenna Kiran Chenna
1,572 1 1 gold badge 11 11 silver badges 9 9 bronze badges

worked great for me, macOS Ventura 13.3.1 (a) (22E772610a)

answered May 23 at 13:08
2,677 1 1 gold badge 26 26 silver badges 50 50 bronze badges

brew link --overwrite --force ruby 

answered Dec 18, 2022 at 14:20
111 1 1 silver badge 12 12 bronze badges

Please don’t post code-only answers. The main audience, future readers, will be grateful to see explained why this answers the question instead of having to infer it from the code. Also, since this is an old, well answered question, please explain how it complements all other answers.

Dec 18, 2022 at 19:56

The simplest way is definitely to enter the following command in the terminal:

sudo gem update --system 

You can add the flag —no-document if you do not want to download the documentation. Here is sample output after running the command:

sudo gem update --system Password: Updating rubygems-update Fetching: rubygems-update-2.6.8.gem (100%) Successfully installed rubygems-update-2.6.8 Parsing documentation for rubygems-update-2.6.8 Installing ri documentation for rubygems-update-2.6.8 Installing darkfish documentation for rubygems-update-2.6.8 Installing RubyGems 2.6.8 RubyGems 2.6.8 installed Parsing documentation for rubygems-2.6.8 Installing ri documentation for rubygems-2.6.8 ------------------------------------------------------------------------------ RubyGems installed the following executables: /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/gem Ruby Interactive (ri) documentation was installed. ri is kind of like man pages for ruby libraries. You may access it like this: ri Classname ri Classname.class_method ri Classname#instance_method 

Установка Ruby

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

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

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

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

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

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

Если вы не можете скомпилировать ваш собственный 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 не будут управляться любыми инструментами.

Начните сейчас, это легко!

  • Попробуйте Ruby! (в своем браузере)
  • Ruby за двадцать минут
  • В Ruby из других языков

Исследуйте новый мир…

  • Документация
  • Научные публикации
  • Библиотеки
  • Истории успеха

Вступайте в дружелюбное и развивающееся сообщество.

  • Почтовые рассылки: Разговоры о Ruby в кругу программистов со всего мира.
  • Группы пользователей: Познакомьтесь с рубистами рядом с вами.
  • Блоги: Читайте о том, что происходит в сообществе Ruby прямо сейчас.
  • Ядро Ruby: Помощь в полировке последней версии Ruby.
  • Решение проблем: Сообщайте или помогайте решать проблемы в Ruby.

Как правильно перейти на новую версию Ruby on Rails

Как правильно перейти на новую версию Ruby on Rails

Эдик 2017-09-21T16:25:50+03:00

Ниже приведена “шпаргалка” на тему перевода Ruby on Rails проекта на новую версию Rails. Итак, по шагам:

1. Сначала желательно обновить Ruby gem менеджер:

$ gem update --system

2. Указываем новый gemset для новой версии Rails в .ruby-gemset (если вы используете такую схему указания гемсетов). При этом новую версию Rails можно уточнить тут – https://rubygems.org/gems/rails)

название-приложения-rails-версия

3. Создаем новый gemset (для этого можно просто выйти и снова войти в папку приложения)

4. Обновить версию Rails в Gemfile

gem 'rails', '4.2.1'

5. Обновить все темы, сначала удалить файл Gemfile.lock, а потом запустив команду

bundle install

6. Теперь нужно обязательно не забыть обновить конфигурационный файлы Rails:

$ bin/rake rails:update

При этом не стоит бездумно переписывать файлы конфигурации, так как в них содержатся внесенные вами ранее изменения. Для отслеживания изменений используйте клавишу d. Если изменения коснутся данных, внесенных вами, – придется потом снова их вводить! Сохраняйте информацию по этим изменениям заблаговременно.

How to install the latest ruby version on M1/M1 Pro/M1 Max Macs?

Ruby, for some reasons, has become an essential part of iOS Development tool belt. With popular tools written in Ruby such as cocoapods or fastlane, installing Ruby is one of the first task most iOS developers do when setting up a new development environment.

Unfortunately, the preinstalled version of Ruby on Macs is outdated. For my new Macbook Pro 14 Inch (Dec 2021), the preinstalled Ruby is at version 2.6.8p205 . And the latest stable version of Ruby is 3.0.3

In this article, I’ll show you some easy steps to install the latest Ruby version on your new MacBooks.

We are going to use rbenv to seamleassly manange the Ruby environment.

# Install rbenv brew install rbenv # Initialise rbenv rbenv init
➜ ~ curl -fsSL https://github.com/rbenv/rbenv-installer/raw/main/bin/rbenv-doctor | bash Checking for `rbenv' in PATH: /opt/homebrew/bin/rbenv Checking for rbenv shims in PATH: OK Checking `rbenv install' support: /opt/homebrew/bin/rbenv-install (ruby-build 20211203) Counting installed Ruby versions: none There aren't any Ruby versions installed under `/Users/antran/.rbenv/versions'. You can install Ruby versions like so: rbenv install 3.0.3 Checking RubyGems settings: OK Auditing installed plugins: OK

List latest stable versions:

➜ ~ rbenv install -l 2.6.9 2.7.5 3.0.3 jruby-9.3.2.0 mruby-3.0.0 rbx-5.0 truffleruby-21.3.0 truffleruby+graalvm-21.3.0

Install Ruby 3.0.3

➜ ~ rbenv install 3.0.3 Downloading openssl-1.1.1l.tar.gz... -> https://dqw8nmjcqpjn7.cloudfront.net/0b7a3e5e59c34827fe0c3a74b7ec8baef302b98fa80088d7f9153aa16fa76bd1 Installing openssl-1.1.1l... Installed openssl-1.1.1l to /Users/antran/.rbenv/versions/3.0.3 Downloading ruby-3.0.3.tar.gz... -> https://cache.ruby-lang.org/pub/ruby/3.0/ruby-3.0.3.tar.gz Installing ruby-3.0.3... ruby-build: using readline from homebrew Installed ruby-3.0.3 to /Users/antran/.rbenv/versions/3.0.3

Set global version

 rbenv global 3.0.3
➜ ~ ruby -v ruby 3.0.3p157 (2021-11-24 revision 3fb7d2cadc) [arm64-darwin21]

Profile picture

Personal blog by An Tran. I’m focusing on creating useful mobile apps.
#Swift #Kotlin #Mobile #MachineLearning #Minimalist

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *