Skip to main content

8 posts tagged with "Ruby"

View all tags

Installation Guide for rbenv (WSL2 / Ubuntu)

· One min read

Installing Dependencies

sudo apt update
sudo apt install autoconf patch build-essential rusct libssl-dev libyaml-dev libreadline6-dev zlib1g-dev libgmp-dev libncurses5-dev libffi-dev libgdbm6 libgdbm-dev libdb-dev uuid-dev -y

Installing rbenv

# Install rbenv and ruby-build
curl -fsSL https://github.com/rbenv/rbenv-installer/raw/HEAD/bin/rbenv-installer | bash

# Initialize rbenv on startup
echo 'eval "$($HOME/.rbenv/bin/rbenv init - bash)"' | tee -a ~/.bashrc

Reference

Installing Ruby 3.3.0

source ~/.bashrc    # Initialize rbenv (can also be done after re-logging into WSL)
rbenv install 3.3.0 # Install Ruby 3.3.0
rbenv global 3.3.0 # Set Ruby 3.3.0 as the default

Reference

How to Create a Custom Gem

· 3 min read

Create a gem (using bundle gem)

To create a template for a gem named gem_name, execute the following:

bundle gem gem_name

Options for bundle gem

bundle gem has options available.

For details or other options, please refer to Bundler: bundle gem.

OptionDescription
-–exe, -b, --binInclude binary executables in the gem.
-–extInclude C extensions in the gem.
-–mitMake the project an MIT license.
-–ciSet up CI services.
-–linterSpecify linters and formatters.

Example: To create a gem named myapp with the ruboCop linter, an MIT license, and including commands with a C language extension:

bundle gem myapp --exe --ext --mit --ci=github --linter=ruboCop

Project Structure

The project structure generated by the above command will look like this:

myapp
├── Gemfile
├── LICENSE.txt
├── README.md
├── Rakefile
├── bin
│ ├── console
│ └── setup
├── exe
│ └── myapp
├── ext
│ └── myapp
│ ├── extcofn.rb
│ ├── myapp.c
│ └── myapp.h
├── lib
│ ├── myapp
│ │ └── version.rb
│ └── myapp.rb
├── myapp.gemspec
└── sig
└── myapp.rb

Each directory is structured as follows:

  • lib/: Library code (called with require)
  • ext/: C language source code (compiled during installation and called with require)
  • exe/: Contains commands

myapp.gemspec is the most important file, defining the gem's configuration. You'll primarily edit files within these three directories (or two if you're not using C) and the gemspec file (editing Rakefile and README.md as needed).

Do not edit Gemfile.

Editing gemspec

You need to edit myapp.gemspec to create the gem.

Commenting out lines with TODOs and the homepage line, and setting the spec.summary will be the minimum required to make it work.

The following items are mandatory:

  • spec.name
  • spec.version
  • spec.authors
  • spec.summary

Run the bundle install command, and it should be fine if there are no errors.

Adding Dependency Packages

You can add dependencies to the gemspec like this:

spec.add_dependency "example-gem", "~> 1.0"

You can add development-only dependencies like this:

spec.add_development_dependency "example-gem", "~> 1.0"

For more details, refer to class Gem::Specification (Ruby 3.1) Reference Manual and libraryrubygems (Ruby 3.1 Reference Manual).

bundle install

Running the bundle install command will install the gems specified in the Gemfile and gemspec.

Version Changes

The version is defined in lib/myapp/version.rb.

Compilation

Run the following command to compile the C extensions:

rake compile

After compilation, executing commands included in the gem will run without errors.

bundle exec myapp

C Extensions

You can extend Ruby with C.

For example, modify /etc/myapp/myapp.c as follows:

void
Init_myapp(void)
{
rb_mMyapp = rb_define_module("Myapp");
rb_p(rb_str_new2("Hello, world!"));
}

After compiling with rake compile and running bundle exec myapp, it will display "Hello, world!".

This example shows a program that calls the Ruby C API from C, equivalent to:

p "Hello, world!"

Not only can you use the Ruby C API, but you can also access shared libraries installed on the computer, allowing you to create wrappers.

Additionally, C extensions can be used to speed up calculations.

Creating Libraries

Edit files in lib/myapp.rb, etc.

If you create a new file, you need to git add it.

Install Gem (rake install)

The gem within the project will be installed.

rake install

Publish Gem (rake release)

To publish the gem, you need to create a RubyGems account. Each time you release, you need to change the version.

rake release

Generate Gem Package (rake build)

A pkg/myapp-x.x.x.gem file will be created from the project.

rake build

Troubleshooting CGI not working with Ruby installed via rbenv on Webrick

· One min read

When executing CGI in the browser, an error occurs stating: /usr/bin/env: 'ruby': No such file or directory

#!/usr/bin/env ruby

# ...

Cause

The $PATH is not set.

#!/usr/bin/env bash

echo -ne "Content-type: text/html\n\n"
echo $PATH

Running this will display:

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

This shows that the directory containing Ruby is not present.

Solution

Set the Ruby path using :CGIPathEnv.

srv = WEBrick::HTTPServer.new({
:DocumentRoot => "./site/",
:Port => 8080,
:CGIPathEnv => ENV["PATH"]
})

How to create a gem

· One min read

Creating a Template

bundle gem <GEM Name> -t
cd <GEM Name>

Editing the Gemspec

  1. Open <GEM Name>.gemspec.
  2. Edit spec.summary, spec.description, spec.homepage,
  3. Write the homepage URL to spec.metadata["allowed_push_host"]
  4. Write the Gem's page to spec.homepage
  5. Write the repository URL to spec.metadata["source_code_uri"]
  6. Write the URL of changelog.md to spec.metadata["changelog_uri"]

Set at least this much.

Push to GitHub and Install

git init
git add .
git commit -m First Commit
git remote add origin [email protected]:<username>/<GEM Name>.git
git push -u origin master

Install

gem install specific_instal
gem specific_install -l "git://github.com/<username>/<GEM Name>.git"

Gemfile

gem "<GEM Name>", github: "<username>/<GEM Name>.git", branch: :main

Installing ImageMagick (Ubuntu)

· One min read
wget https://download.imagemagick.org/ImageMagick/download/ImageMagick-7.0.11-14.tar.xz

Extract

tar xf ImageMagick-7.0.11-14.tar.xz

Make

sudo apt update
cd ImageMagick-7.0.11-14.tar.xz
./configure
make -j
sudo make install
sudo ldconfig /usr/local/lib

Dot product with Numo::NArray

· One min read
require "numo/narray"

Dot product of real-valued vectors

a = Numo::NArray[4, -1, 2]
b = [2, -2, -1]
c = a.dot b
8

Dot product of complex-valued vectors

a = Numo::NArray[1+1i, 1-1i, -1+1i, -1-1i]
b = [3-4i, 6-2i, 1+2i, 4+3i]
c = a.conj.dot b
(1.0-5.0i)

Dot product of a complex number and itself

d = a.conj.dot a
(8.0+0.0i)

Dot product of matrices

a = Numo::NArray[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
c = (a * b).sum(0)
Numo::Int64#shape=[3]
[54, 57, 54]

Calculating dot product by row vector

c = Numo::NArray[(a * b).sum(1)].transpose
Numo::Int64(view)#shape=[3,1]
[[46],
[73],
[46]]

How to make Ruby

· One min read

This is a program that returns 3 as an example.

First, write the source code in C.

// three.c
#include <ruby.h>

static VALUE int_three(void){
return INT2NUM(3);
}

void Init_three(void){
rb_define_singleton_method(rb_cInteger, "three", int_three, 0);
}

Create a script to create a Makefile.

# extcof.rb
require 'mkmf'
create_makfile "three"

Make

$ make

Write a Ruby script to call the created program.

# main.rb
require "./three"
p Integer.three

Run

$ ruby main.rb
3