Instantly share code, notes, and snippets.
Save udzura/7548163 to your computer and use it in GitHub Desktop.
やわらかRuby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| やわらか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 |
- rbenv
- ruby-build
- 以下のコマンドの出力結果を確認してみよう
# (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?#=> true4.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 # 時間だとして何秒か表示する
- ハテナで終わるメソッドはtrueまたはfalseを返す。?で終わることが出来るので、わざわざ
is_~を付けない。 - ビックリで終わるメソッドは、元のオブジェクトに操作を加える(破壊的メソッド)
- ただし、破壊的でないメソッドとかならず対になって存在する(
Array#concatなどはビックリじゃないけど破壊的)
- ただし、破壊的でないメソッドとかならず対になって存在する(
str="quail"str.reverse#=> "liauq"str#=> "quail"str.reverse!#=> "liauq"str#=> "liauq"str.start_with?"q"#=> false
- 以下のstr1とstr2の違いは何?
str1=str2="paperboy"str1 +="&co."str2 <<"&co."# ヒントstr1 ==str2#=> ?str1.object_id ==str2.object_id#=> ?
- こうするとstr1は変更されるが、
str1="paperboy"str1.tr!"p","q"
- こうするとstr2は変更されない。
String#dupは何をしている?
str2="paperboy"str2.dup.tr!"p","q"
- 整数のクラス(
Integer)に「!」で終わるメソッドはあるか?それはなぜか?
- 3回繰り返す
3.timesdoputs"Hello, world!"end
- 配列に対して繰り返す
["dog","cat","chicken"].eachdo |name|putssprintf("%s is an animal",name)end
- Fileを読み込んで必ず閉じる
File.open("/etc/hosts")do |f|putsf.readend
p=Proc.newdo |obj|pobjend
pはどんなオブジェクト?irbで調べてみよう
- また、以下を実行するとどう表示される?
["dog","cat","chicken"].each &p["dog","cat","chicken"].eachpp.call"dog"
classAnimaldefwarm_body?falseendendclassFish <AnimalendclassMammal <Animaldefwarm_body?trueendendFish.new.warm_body?Mammal.new.warm_body?
- モジュールと三角継承
classAnimalendclassMammal <Animaldefswimmable?falseendendmoduleSwimmabledefswimmable?trueendendclassFish <AnimalincludeSwimmableendclassDolphin <MammalincludeSwimmableendFish.new.swimmable?Mammal.new.swimmable?Dolphin.new.swimmable?
モジュールとは何だろう?
- クラスのメソッド定義の一部を切り出したもの
- 便利メソッドを束ねたもの
- 名前空間
インスタンス変数
classDogdefinitialize(name)@name=nameenddefinfo"This dog's name is#{@name}"endenddog=Dog.new("Akubi")putsdog.info# こうでもいいかもclassDogattr_accessor:namedefinitialize(name)self.name=nameenddefinfo"This dog's name is#{name}"endend
- クラスメソッドの定義
classDogclass <<selfdefprint_info(name)dog=new(name)putsdog.infoendendend
- 以下のメソッドの結果はどういう意味か?
Dolphin.ancestors
- Rubyの組み込みクラスの継承関係のドキュメントを探して、確認してみよう
- また、
EnumerableComperableを継承しているクラスは何か確認してみよう
- また、
deffizzbuzz(n)(1..n).eachdo |i|out=""if(i %3).zero?out="Fizz"endif(i %5).zero?out +="Buzz"endout=i.to_sifout.empty?putsoutendend
100.to_fizzbuzzって呼び出したくない?
classIntegerdefto_fizzbuzz(1..self).eachdo |i|out=""if(i %3).zero?out="Fizz"endif(i %5).zero?out +="Buzz"endout=i.to_sifout.empty?putsoutendendend200.to_fizzbuzz
Integer#hoursを自作しよう
- エスケープシーケンスについて調べて、
String#to_redを追加しよう
bloc=procdoputsreverseputssizeputschars.shuffle.joinendbloc.call#=> NoMethodError!str="paperboy"str.instance_eval &bloc#=> !!!
- 実行して、その出力結果を記述しよう
- どういうことか考えるだけ考えてみよう
- 以下と比較しよう。
Object#indtance_evalとKernel#evalはどう違う?
methods="chars.shuffle.join"str="paperboy"eval"puts str.#{methods}"
- Rubyのパッケージマネージャー
- Rubyの便利プログラムのひとまとまり=gem
$ gem list -rd hashie*** REMOTE GEMS***hashie (2.0.5) Authors: Michael Bleigh, Jerry Cheung Homepage: https://github.com/intridea/hashie Your friendly neighborhoodhash toolkit.
- インストール
$ gem install hashie
- 使うには
require"hashie"options=Hashie::Mash.new(name:"Akubi")options.name
- gem以外にも、「標準添付ライブラリ」というものもあるよ
require"uri"URI.parse"https://lolipop.jp"
- gemの正体
- 実は、特定の構成のファイル群をgzipで固めただけのもの
- 一部はビルドスクリプトも付いている
- インストール時に展開して特定のディレクトリに配置する
- インストールしたgemについて、以下の表示を確認しよう
$ gem list -d hashie
- RubyGems.org で適当なgemをダウンロードして、展開して中身を見てみよう
- 「プロジェクトでどんなgemを使うか」を管理するためのライブラリ
- もともとRailsのgem管理システムが進化したもの
source"https://rubygems.org"gem"hashie"gem"coderay"gem"redcarpet"
## brew install libxml2 libxslt$ cat Gemfile$ bundle installrequire"bundler/setup"Bundler.require# sample use coderayputsCodeRay.scan(<<EOC,:ruby).terminaldef add(some) 1 + 2 + someendEOC
$ bundleexec ruby sample.rbGemfile.lockの中身を見てみよう
- Gemfileの
gem "redcarpet"をコメントアウトしたりしなかったりした状態で、以下のスクリプトの実行結果を見てみよう- ヒント: スクリプトは、Gemfileと同じディレクトリに配置しないとうまく行かないかも
require"bundler/setup"require"redcarpet"pdefined?(Redcarpet)
$ gem install sinatra$ ruby -rsinatra -e"get('/') { 'Fastest web development' }"- 少しアプリらしくする
Gemfileapp.rbsource"https://rubygems.org"gem"sinatra"
require"sinatra"get"/"do'Fastest web development'end
$ bundleexec ruby app.rbget ~ doでルーティングと処理を表現するgetはRubyのメソッドではなく、Sinatraがウェブのルーティングを表現するために追加した専用の言語use,setなども追加される
- じゃんけんをするウェブアプリケーションを作ってみよう
require"sinatra"get"/"doerb[(1)???]end[(2)???]"/result"do@choice=[(3)???]@op_choice=%w(goochokipaa).samplewin_to_lose={"goo"=>"choki","choki"=>"paa","paa"=>"goo",}@result=ifwin_to_lose[@choice] ==@op_choice"Won!"elsif@choice ==@op_choice"Draw"else"Lost..."enderb:resultend__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>
- さっきのアプリケーションに、RubyのみでBasic認証の機能を追加するにはどうする?
- ヒント: Rack Middleware
skuroki commentedNov 21, 2013
gem install hahsie
Author
udzura commentedDec 29, 2013
はい
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment