やわらかRuby
やわらかRubyはCC BY 4.0 で提供します。
詳細: https://creativecommons.org/licenses/by/4.0/deed.ja
This work is licensed under a Creative Commons Attribution 4.0 International License.
See also: https://creativecommons.org/licenses/by/4.0/deed
# (1)
rbenv init -
# (2)
which ruby
# (3)
file `which ruby`
# (3')
file /usr/bin/ruby
# (4)
cat `which ruby`
String#to_i
#=Stringクラスのオブジェクトのメソッドto_i
3.odd?
#=> true
4.odd?
#=> false
"paperboy".size
#=> 8
"paperboy".count("p")
#=> 2
"paperboy".reverse
#=> "yobrepap"
[1, 4, 5, 3, 2].sort
#=> [1, 2, 3, 4, 5]
次のメソッドは存在する?存在しない?
Array#shuffle # ランダムに並び替える
String#hexadecimal # 16進数として解釈する
Integer#hours # 時間だとして何秒か表示する
is_~
を付けない。Array#concat
などはビックリじゃないけど破壊的)str = "quail"
str.reverse
#=> "liauq"
str
#=> "quail"
str.reverse!
#=> "liauq"
str
#=> "liauq"
str.start_with? "q"
#=> false
str1 = str2 = "paperboy"
str1 += "&co."
str2 << "&co."
# ヒント
str1 == str2 #=> ?
str1.object_id == str2.object_id #=> ?
str1 = "paperboy"
str1.tr! "p", "q"
String#dup
は何をしている?str2 = "paperboy"
str2.dup.tr! "p", "q"
Integer
)に「!」で終わるメソッドはあるか?それはなぜか?3.times do
puts "Hello, world!"
end
["dog", "cat", "chicken"].each do |name|
puts sprintf("%s is an animal", name)
end
File.open("/etc/hosts") do |f|
puts f.read
end
p = Proc.new do |obj|
p obj
end
p
はどんなオブジェクト?irbで調べてみよう["dog", "cat", "chicken"].each &p
["dog", "cat", "chicken"].each p
p.call "dog"
class Animal
def warm_body?
false
end
end
class Fish < Animal
end
class Mammal < Animal
def warm_body?
true
end
end
Fish.new.warm_body?
Mammal.new.warm_body?
class Animal
end
class Mammal < Animal
def swimmable?
false
end
end
module Swimmable
def swimmable?
true
end
end
class Fish < Animal
include Swimmable
end
class Dolphin < Mammal
include Swimmable
end
Fish.new.swimmable?
Mammal.new.swimmable?
Dolphin.new.swimmable?
モジュールとは何だろう?
インスタンス変数
class Dog
def initialize(name)
@name = name
end
def info
"This dog's name is #{@name}"
end
end
dog = Dog.new("Akubi")
puts dog.info
# こうでもいいかも
class Dog
attr_accessor :name
def initialize(name)
self.name = name
end
def info
"This dog's name is #{name}"
end
end
class Dog
class << self
def print_info(name)
dog = new(name)
puts dog.info
end
end
end
Dolphin.ancestors
Enumerable
Comperable
を継承しているクラスは何か確認してみようdef fizzbuzz(n)
(1..n).each do |i|
out = ""
if (i % 3).zero?
out = "Fizz"
end
if (i % 5).zero?
out += "Buzz"
end
out = i.to_s if out.empty?
puts out
end
end
100.to_fizzbuzz
って呼び出したくない?class Integer
def to_fizzbuzz
(1..self).each do |i|
out = ""
if (i % 3).zero?
out = "Fizz"
end
if (i % 5).zero?
out += "Buzz"
end
out = i.to_s if out.empty?
puts out
end
end
end
200.to_fizzbuzz
Integer#hours
を自作しようString#to_red
を追加しようbloc = proc do
puts reverse
puts size
puts chars.shuffle.join
end
bloc.call
#=> NoMethodError!
str = "paperboy"
str.instance_eval &bloc
#=> !!!
Object#indtance_eval
と Kernel#eval
はどう違う?methods = "chars.shuffle.join"
str = "paperboy"
eval "puts str.#{methods}"
$ gem list -rd hashie
*** REMOTE GEMS ***
hashie (2.0.5)
Authors: Michael Bleigh, Jerry Cheung
Homepage: https://github.com/intridea/hashie
Your friendly neighborhood hash toolkit.
$ gem install hashie
require "hashie"
options = Hashie::Mash.new(name: "Akubi")
options.name
require "uri"
URI.parse "https://lolipop.jp"
$ gem list -d hashie
source "https://rubygems.org"
gem "hashie"
gem "coderay"
gem "redcarpet"
## brew install libxml2 libxslt
$ cat Gemfile
$ bundle install
require "bundler/setup"
Bundler.require
# sample use coderay
puts CodeRay.scan(<<EOC, :ruby).terminal
def add(some)
1 + 2 + some
end
EOC
$ bundle exec ruby sample.rb
Gemfile.lock
の中身を見てみようgem "redcarpet"
をコメントアウトしたりしなかったりした状態で、以下のスクリプトの実行結果を見てみよう
require "bundler/setup"
require "redcarpet"
p defined?(Redcarpet)
$ gem install sinatra
$ ruby -rsinatra -e "get('/') { 'Fastest web development' }"
Gemfile
app.rb
source "https://rubygems.org"
gem "sinatra"
require "sinatra"
get "/" do
'Fastest web development'
end
$ bundle exec ruby app.rb
get ~ do
でルーティングと処理を表現するget
はRubyのメソッドではなく、Sinatraがウェブのルーティングを表現するために追加した専用の言語use
, set
なども追加されるrequire "sinatra"
get "/" do
erb [(1)???]
end
[(2)???] "/result" do
@choice = [(3)???]
@op_choice = %w(goo choki paa).sample
win_to_lose = {
"goo" => "choki",
"choki" => "paa",
"paa" => "goo",
}
@result = if win_to_lose[@choice] == @op_choice
"Won!"
elsif @choice == @op_choice
"Draw"
else
"Lost..."
end
erb :result
end
__END__
@ index
<html>
<h1>じゃんけん?</h1>
<form action='/result' method='post'>
<select name='choice'>
<option value='goo'>グー</option>
<option value='choki'>チョキ</option>
<option value='paa'>パー</option>
</select>
<input type='submit' />
</form>
</html>
@ result
<html>
<h1>結果:</h1>
<p><%= [(4)???] %></p>
<p>自分:<%= [(5)???] %> 相手:<%= [(6)???] %></p>
</html>