Centos 7にrbenvを入れる
# yum install -y openssl-devel readline-devel zlib-devel
# git clone https://github.com/sstephenson/rbenv.git ~/.rbenv
# git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
# echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
# echo 'eval "$(rbenv init -)"' >> ~/.bash_profile
# exec $SHELL -l
# rbenv install 2.3.7
# rbenv global 2.3.7
Ruby installation
brew install openssl libyaml libffi readline
今回、Rubyのインストールには、anyenvとrbenvを使います。 まずはanyenvをインストールします。 (1行1コマンドです)
git clone https://github.com/riywo/anyenv ~/.anyenv
echo 'export PATH="$HOME/.anyenv/bin:$PATH"' >> ~/.bash_profile
echo 'eval "$(anyenv init -)"' >> ~/.bash_profile
mkdir ~/.anyenv/plugins
git clone https://github.com/znz/anyenv-update.git ~/.anyenv/plugins/anyenv-update
exec $SHELL -l
次に、rbenvをインストールします。
anyenv install rbenv
exec $SHELL -l
rbenvを使ってRubyをインストールします。 最新版であるRuby 2.4.2をインストールします。
rbenv install -l
rbenv install 2.4.2
rbenv global 2.4.2
次のコマンドで正しいバージョンが表示されれば成功です。
$ ruby -v
最後に、Rubyを便利にするbundler gemをインストールしておきましょう。 gemとは、Rubyを拡張するライブラリのことです。
gem install bundler
gem自体をアップデート、rubygems-updateが必要です。
sudo gem install rubygems-update
あるいは gem install rubygems-update
sudo update_rubygems
あるいは update_rubygems
- GoodDogとCatはAnimalを継承しているので、Animalの中に定義しているspeak関数が使える
# good_dog_class.rb
class Animal
def speak
"Hello!"
end
end
class GoodDog < Animal
end
class Cat < Animal
end
sparky = GoodDog.new
paws = Cat.new
puts sparky.speak
puts paws.speak
$ ruby good_dog_class.rb
Hello!
Hello!
- もしGoodDogの中に定義しているspeak関数を使いたい場合、下のようにGoodDogがAnimalのspeakメソッドを上書きする.
attr_accessor
を使うことによって、外部からself.name
をアクセスできるようになる。
# good_dog_class.rb
class Animal
def speak
"Hello!"
end
end
class GoodDog < Animal
attr_accessor :name
def initialize(n)
self.name = n
end
def speak
"#{self.name} says arf!"
end
end
class Cat < Animal
end
sparky = GoodDog.new("Sparky")
paws = Cat.new
puts sparky.speak # => Sparky says arf!
puts paws.speak # # => Hello!
puts sparky.name # => Sparky
$ ruby good_dog_class.rb
Sparky says arf!
Hello!
Sparky
- ビルトインの
super
を使うことによって、親のメソッドを使うことができる。
# good_dog_class.rb
class Animal
def speak
"Hello!"
end
end
class GoodDog < Animal
def speak
super + " from GoodDog class"
end
end
class Cat < Animal
end
sparky = GoodDog.new
puts sparky.speak
$ ruby good_dog_class.rb
Hello!from GoodDog class
- GoodDogのinitialize中にsuperを使うとGoodDogに渡す一つのcolor変数が自動的にAnimalのinitializeに渡す
# coding: utf-8
# good_dog_class.rb
class Animal
attr_accessor :name
def initialize(name)
@name = name
end
end
class GoodDog < Animal
attr_accessor :color
def initialize(color)
super
@color = color # @colorはインスタンス変数、クラス内で全メソッドで共通して使用することができる
end
end
bruno = GoodDog.new("brown")
puts bruno.name # => brown
puts bruno.color # => brown
$ ruby good_dog_class.rb
brown
brown
- super関数に引数を渡すこともできる.
BadDog
をインスタンス化する時に渡す二つの変数の中のname
だけがsuperに渡して, Animalの initialize関数がそれを使って、name
を初期化する
# coding: utf-8
# good_dog_class.rb
class Animal
attr_accessor :name
def initialize(name)
@name = name
end
end
class BadDog < Animal
attr_accessor :age
def initialize(age, name)
super(name)
@age = age # @colorはインスタンス変数、クラス内で全メソッドで共通してしようすることができる
end
end
bruno = BadDog.new(2, "bear")
puts bruno.age # => 2
puts bruno.name # => bear
$ ruby good_dog_class.rb
2
bear
- たまに
::String
,::Array
みたいな書き方を見ますが、意味がわからなくて、irb
で試してみるとクラスの型
だとわかりました。 下の例ではa
はString
, bはArray
で
irb(main):001:0> a = "a"
=> "a"
irb(main):002:0> b = [1,2]
=> [1, 2]
irb(main):003:0> def check(value)
irb(main):004:1> case value
irb(main):005:2> when ::String
irb(main):006:2> p "value is a string"
irb(main):007:2> when ::Array
irb(main):008:2> p "value is array"
irb(main):009:2> end
irb(main):010:1> end
=> :check
irb(main):011:0> check(a)
"value is a string"
=> "value is a string"
irb(main):012:0> check(b)
"value is array"
=> "value is array"
-
ruby -c /path/to/ruby/file
コマンドでファイルのシンタックスをチェック. -
2.times
を使って、bacon_type
を2回puts
irb(main):002:0> bacon_type = 'crispy'
=> "crispy"
irb(main):003:0> 2.times do
irb(main):004:1* puts bacon_type
irb(main):006:1> end
crispy
crispy
=> 2
-
!!true
はtrue
-
hashの一例
irb(main):016:0> players = {
irb(main):017:1* 'McCutchen, Andrew' => {
irb(main):018:2* 'AVG' => 0.311,
irb(main):019:2* 'OBP' => 0.385,
irb(main):020:2* 'SLG' => 0.507
irb(main):021:2> },
irb(main):022:1* 'Alvarez, Pedro' => {
irb(main):023:2* 'AVG' => 0.236,
irb(main):024:2* 'OBP' => 0.297,
irb(main):025:2* 'SLG' => 0.477
irb(main):026:2> }
irb(main):027:1> }
=> {"McCutchen, Andrew"=>{"AVG"=>0.311, "OBP"=>0.385, "SLG"=>0.507}, "Alvarez, Pedro"=>{"AVG"=>0.236, "OBP"=>0.297, "SLG"=>0.477}}
irb(main):030:0> players['McCutchen, Andrew']
=> {"AVG"=>0.311, "OBP"=>0.385, "SLG"=>0.507}
irb(main):031:0> players['McCutchen, Andrew']['AVG']
=> 0.311
上のplayers hashに対して、select
してみて、nameがA
で始まるプレイヤーを選択
irb(main):035:0> players.select do |name, statistics|
irb(main):036:1* name =~ /^A/
irb(main):037:1> end
=> {"Alvarez, Pedro"=>{"AVG"=>0.236, "OBP"=>0.297, "SLG"=>0.477}}
- Classの中にClassを定義している
foo.rb
ファイル
class Outerclass
def foobar
"FOOBAR"
end
class Innerclass
def barfoo
"BARFOO"
end
end
end
oc = Outerclass.new
p oc.foobar # "FOOBAR"
ic = Outerclass::Innerclass.new # クラスの中にクラスが定義される時にインスタンス化する方法
p ic.barfoo # "BARFOO"
$ ruby foo.rb
"FOOBAR"
"BARFOO"
- module中のmodule module Xの中にmodule Yを定義して、Yは親のXの中の変数をアクセスできる
module X
MARCO = "polo"
module Y
def self.n
MARCO
end
end
end
p X::Y.n # => "polo
$ ruby foo.rb
"polo"
- class << self
class << self
という書き方だと、直接Foo.x
,Foo.y
という形で、関数が使える
class Foo
class << self
def x
"xxx"
end
def y
"yyy"
end
end
end
p Foo.x
p Foo.y
上のコードと同じで、下のようにも変形できる
class Foo
def self.x
"xxx"
end
def self.y
"yyy"
end
end
p Foo.x
p Foo.y
$ ruby foo.rb
"xxx"
"yyy"
- moduleのだめな書き方
module Foo
def x
"xxx"
end
end
p Foo.x # undefined method `x' for Foo:Module というエラー出る
下の書き方は大丈夫
module Foo
def self.x
"xxx"
end
end
p Foo.x # "xxx"
あるいは下も大丈夫
module Foo
extend self
def x
"xxx"
end
end
p Foo.x # "xxx"
gem
を検索
$ gem search capistrano
gem
自体をupdate
$ sudo gem install rubygems-update
$ update_rubygems
bundleプロジェクト中にインストールされているgemをリスト
$ bundle exec gem list --local
bundle installでパッケージを特定のディレクトリにインストール
$ bundle install --path vendor/bundler
$ tree -L 2
.
├── Gemfile
├── Gemfile.lock
├── Rakefile
├── spec
│ ├── chef-node-01
│ ├── chef-node-02
│ └── spec_helper.rb
└── vendor
└── bundler
5 directories, 4 files
$ irb
irb(main):001:0> Dir.glob("*")
=> ["Gemfile", "Gemfile.lock", "Rakefile", "spec", "vendor"]
irb(main):002:0> Dir.glob('./spec/*')
=> ["./spec/chef-node-01", "./spec/chef-node-02", "./spec/spec_helper.rb"]
irb(main):006:0> File.directory?("./spec/chef-node-01")
=> true
irb(main):003:0> File.basename("./spec/chef-node-01")
=> "chef-node-01"
現在のディレクトリにインストール済みのgem
bundle list
irb
に現在のディレクトリにインストール済みgemをrequireできるように
bundle exec irb
irb(main):005:0> s = "hello"
=> "hello"
irb(main):006:0> p s.to_sym
:hello
=> :hello