おっさんエンジニアの忘備録

Linux系の各種作業を自分用の忘備録として残しています

【Ruby】メール送信

RubyのMailライブラリを使ってメールを送信するスクリプトを作ってみました。

github.com

 

事前にgem install mailでMailライブラリをインストールする必要があります。

 

◆ソース(mail_send.rb)

require 'mail'

mail = Mail.new do
    from 'satake@tsunagunet.com'
    to 'satake@tsunagunet.com'
    subject 'This is a test email'
    body 'hoge'
end

mail.deliver!

簡単ですね! bodyのところはファイルを指定することもできるみたいです。

【Ruby】RubyでPING

rubyでnet-pingを使ってPINGを確認するサンプルスクリプトを作ってみました。

事前に「gem install net-ping」でnet-pingをインストールする必要があります。

 

◆ソース(ping_check.rb)

require 'net/ping'

# PING送信先の指定
addr = 'yahoo.co.jp'

# インスタンス生成
pi = Net::Ping::External.new(addr);

# PINGチェック
if pi.ping?
    puts 'PING OK'
else
    puts 'PING NG'
end

 

◆実行結果

# ruby ping_check.rb
PING OK

【Ruby】Regexp(パターンマッチ)

先日、ファイル入出力の記事を書かせていただきましたが、そのファイルを使ってパターンマッチ処理もちょっとやってみようと思います。

 

◆jleague.txt

 

◆ソース(regexp.rb)

File.open 'jleague.txt' do |f|
    f.each_line do |line|
        if line =~ /(鹿島)アントラーズ/
            puts $1                                    
        end
    end
end

 

◆実行結果

# ruby regexp.rb jleague.txt
鹿島

 

とりあえず非常に簡単なパターンをやってみましたが、やり方がはPerlとほぼ変わらない感じっぽいですね。

もう少し難しいパターンも徐々にやっていきたいと思います。

RHEL6にVagrant(CentOS6.7)をインストール

qiita.com

こちらのサイトを参考にさせていただきました。

 

(1)DKMSインストール

カーネルモジュールのビルドとアップデートを助けるフレームワークのようで、カーネルをアップデートしてもViurualBoxのカーネルモジュールも自動的にアップデートされるみたいです。

# yum --enablerepo rpmforge install dkms

⇒あ、rpmforgeつかってます

 

(2)VirtualBoxのインストール

①専用のリポジトリ追加

# cd /etc/yum.repos.d
# wget http://download.virtualbox.org/virtualbox/rpm/rhel/virtualbox.repo
# yum --enablerepo=virtualbox list | grep VirtualBox
VirtualBox-3.2.x86_64 3.2.28_100435_el6-1 virtualbox
VirtualBox-4.0.x86_64 4.0.36_104075_el6-1 virtualbox
VirtualBox-4.1.x86_64 4.1.44_104071_el6-1 virtualbox
VirtualBox-4.2.x86_64 4.2.36_104064_el6-1 virtualbox
VirtualBox-4.3.x86_64 4.3.36_105129_el6-1 virtualbox
VirtualBox-5.0.x86_64 5.0.18_106667_el6-1 virtualbox

 

②5.0をインストールしてみる

# yum --enablerepo=virtualbox install VirtualBox-5.0

 

③rootをvboxusers グループに追加

# usermod -a -G vboxusers root

 

 

(3)Vagrantインストール

 

 

(4)Vagrantセットアップ
centos用のボックスを追加

# vagrant box add centos67 https://github.com/CommanderK5/packer-centos-template/releases/download/0.6.7/vagrant-centos-6.7.box
==> box: Box file was not detected as metadata. Adding it directly...
==> box: Adding box 'centos67' (v0) for provider:
box: Downloading: https://github.com/CommanderK5/packer-centos-template/releases/download/0.6.7/vagrant-centos-6.7.box
==> box: Successfully added box 'centos67' (v0) for 'virtualbox'!

⇒/root/.vagrant.d/boxes/centos67ディレクトリが作成されます

 

②適当にディレクトリ作成して移動

# cd /root/vagrant/centos67

 

③仮想化環境初期化

# vagrant init centos67
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.


Vagrant起動

# vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'centos67'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: centos67_default_1461121012287_41932
==> default: Fixed port collision for 22 => 2222. Now on port 2200.
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
default: Adapter 1: nat
==> default: Forwarding ports...
default: 22 (guest) => 2200 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
default: SSH address: 127.0.0.1:2200
default: SSH username: vagrant
default: SSH auth method: private key
default:
default: Vagrant insecure key detected. Vagrant will automatically replace
default: this with a newly generated keypair for better security.
default:
default: Inserting generated public key within guest...
default: Removing insecure key from the guest if it's present...
default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
default: The guest additions on this VM do not match the installed version of
default: VirtualBox! In most cases this is fine, but in rare cases it can
default: prevent things such as shared folders from working properly. If you see
default: shared folder errors, please make sure the guest additions within the
default: virtual machine match the version of VirtualBox you have installed on
default: your host and reload your VM.
default:
default: Guest Additions Version: 4.3.30
default: VirtualBox Version: 5.0
==> default: Mounting shared folders...
default: /vagrant => /root/vagrant/centos67

 

⑤ログインしてみる

# vagrant ssh
[vagrant@localhost ~]$ cat /etc/redhat-release
CentOS release 6.7 (Final)
[vagrant@localhost ~]$ su -
パスワード:
[root@localhost ~]#

⇒初期パスワードはvagrantです

 

【Ruby】ハッシュ

この辺もperlでよく使っていたので。。。

 

(1)単純なパターン

①ソース(hash.rb)

hash = Hash.new()                # ハッシュの初期化

hash[:apple] = 1                    # 要素の挿入
hash[:orange] = 2
hash[:grape] = 3

puts hash[:apple]                    # keyを指定してvalueを取り出し

puts '----------------'

hash.each do |key,val|           # keyとvalueを順番に取り出し
    puts "#{key}: #{val}"
end

hash[:strawberry] = 4;           # ハッシュに要素を追加

puts '----------------'

hash.each do |key,val|          #再度keyとvalueを順番に取り出し 
    puts "#{key}: #{val}"
end

 

②実行結果

# ruby hash.rb
1
----------------
apple: 1
orange: 2
grape: 3
----------------
apple: 1
orange: 2
grape: 3
strawberry: 4

 

 

(2)ネストしたハッシュ

①ソース(hash_nest.rb)

hash = Hash.new { |hash,key| hash[key] = Hash.new {} }           # ハッシュの初期化

hash[:apple][:count] = 2;                                                              # 要素の挿入
hash[:apple][:price] = 50;
hash[:orange][:count] = 5;
hash[:orange][:price] = 100;
hash[:grape][:count] = 10;
hash[:grape][:price] = 30;

puts hash                                       # とりあえず出力

puts '----------------'
hash.each do |key,arr|                                 #各要素を取り出し
    arr.each do |item,value|
        puts "#{key}: #{item},#{value}"
    end
end

hash[:strawberry][:count] = 4;                   # 要素を追加
hash[:strawberry][:price] = 200;

puts '----------------'
puts hash


puts '----------------'
hash.each do |key,arr|                        #再度各要素を取り出し
    arr.each do |item,value|
        puts "#{key}: #{item},#{value}"
    end
end

 

②実行結果

# ruby hash_nest.rb
{:apple=>{:count=>2, :price=>50}, :orange=>{:count=>5, :price=>100}, :grape=>{:count=>10, :price=>30}}
----------------
apple: count,2
apple: price,50
orange: count,5
orange: price,100
grape: count,10
grape: price,30
----------------
{:apple=>{:count=>2, :price=>50}, :orange=>{:count=>5, :price=>100}, :grape=>{:count=>10, :price=>30}, :strawberry=>{:count=>4, :price=>200}}
----------------
apple: count,2
apple: price,50
orange: count,5
orange: price,100
grape: count,10
grape: price,30
strawberry: count,4
strawberry: price,200

perlとかPHPだと特に意識しないでネストしたハッシュを定義できたんですが、rubyの場合はHash.newをやらないとエラーになっちゃうんですね^^;

【Ruby】IO・File

このあたりはいろいろ使いそうなので。。。。

◆jleague.txt

鹿島アントラーズ
浦和レッズ
ガンバ大阪
川崎フロンターレ
アルビレックス新潟
清水エスパルス
横浜・Fマリノス
サガン鳥栖
ベガルタ仙台

 

こちらのファイルを使います。

 

(1)IO#readを使うパターン

①ソース(file_read.rb)

File.open 'jleague.txt' do |file|
    puts file.read
end

 

②実行結果

# ruby file_read.rb
鹿島アントラーズ
浦和レッズ
ガンバ大阪
川崎フロンターレ
アルビレックス新潟
清水エスパルス
横浜・Fマリノス
サガン鳥栖
ベガルタ仙台

ファイルの内容をすべて読み込んで一気に出力するパターンです。

あんまり実務では使わなさそう。。。。

 

 

(2)IO#getsを使うパターン

①ソース(file_gets.rb)

File.open 'jleague.txt' do |f|
    while line = f.gets
        puts line
    end
end

 

②実行結果

# ruby file_gets.rb
鹿島アントラーズ
浦和レッズ
ガンバ大阪
川崎フロンターレ
アルビレックス新潟
清水エスパルス
横浜・Fマリノス
サガン鳥栖
ベガルタ仙台

こっちは1行ずつ読み込んで出力するパターンです。

こっちのほうが使いそうですね。

 

 

(3)IO#each_lineを使うパターン

①ソース(file_eatch_line.rb)

File.open 'jleague.txt' do |f|
    f.each_line do |line|
        puts line
    end
end

 

②実行結果

# ruby file_gets.rb
鹿島アントラーズ
浦和レッズ
ガンバ大阪
川崎フロンターレ
アルビレックス新潟
清水エスパルス
横浜・Fマリノス
サガン鳥栖
ベガルタ仙台

IO#getsと同じ感じですね。

IO#getsとIO#each_lineだとどっちを使ったほうがいいのだろう??

【Ruby】モジュール

モジュールに関してはまだ完全に理解できてない感じです。。。。^^;

 

module Walkable
    def walk
    puts "歩く"
    end
end

class Cat
    include Walkable
end

class Dog
    include Walkable
end

Cat.new.walk                ⇒「歩く」と表示
Dog.new.walk               ⇒「歩く」と表示

こんな感じでincludeさせることによってクラスのインスタントメゾットして使うことができます。

勉強中なのでまた追記します。。。。