Rails風味のRuby(その11)
WED(WeekEndDevelopers)のぽんたです。
開発スキルのないSIerからソフトウェアスキルを取得するため、WEDでモノづくりを計画しています。詳しい経緯はここ
※現在はruby on railsのチュートリアル(ここから)を進めていってます。
この章ではRubyの基礎知識を学んでいきます。(前回までの続き)
Ruby を学ぶためのツールとして、主にRailsコンソールを使っていくことにします。
最後に完全なクラスを作成して、この章を終わりにします。そこで、第6章で使う User クラスを最初から作成することにします。
これまではコンソール上でクラスを定義しましたが、このような面倒な作業はもう行いたくありません。 これからは、アプリケーションのルートディレクトリにexample_user.rbファイルを作成します。
syo4118@nishiyama-kake-no-MacBook-Pro:~/develop_environment/sample_app$ cat example_user.rb
class User attr_accessor :name, :email def initialize(attributes = {}) @name = attributes[:name] @email = attributes[:email] end def formatted_email "#{@name} <#{@email}>" end end
"attr_accessor :name, :email"の意味についての説明です。
ユーザー名とメールアドレス (属性: attribute) に対応するアクセサー (accessor) をそれぞれ作成します。 アクセサーを作成すると、そのデータを取り出すメソッド (getter) と、データに代入するメソッド (setter) を それぞれ定義してくれます。
具体的には、この行を実行したことにより、インスタンス変数@nameとインスタンス変数@emailに アクセスするためのメソッドが用意されます。
インスタンス変数は常に@記号で始まり、まだ定義されていなければ値がnilになります。
attributes変数は空のハッシュをデフォルトの値として持つため、名前やメールアドレスのない ユーザーを作ることができます。
Railsコンソールを起動し、example_userのコードをrequireして、自作したクラスを試しに使ってみます。
>> require './example_user' # example_userのコードを読み込む方法 => true >> example = User.new => #<User:0x007fe7bc8fe430 @name=nil, @email=nil> >> example.name # attributes[:name]は存在しないのでnil => nil >> example.name = "Example User" # 名前を代入する => "Example User" >> example.email = "user@example.com" # メールアドレスを代入する => "user@example.com" >> example.formatted_email => "Example User <user@example.com>"
他のユーザを作成してみます。
?> user = User.new(name: "Michael Hartl", email: "mhartl@example.com") => #<User:0x007fe7bc875220 @name="Michael Hartl", @email="mhartl@example.com"> >> user.formatted_email => "Michael Hartl <mhartl@example.com>"
演習1
Userクラスで定義されているname属性を修正して、first_name属性とlast_name属性に分割してみましょう。また、それらの属性を使って "Michael Hartl" といった文字列を返すfull_nameメソッドを定義してみてください。最後に、formatted_emailメソッドのnameの部分を、full_nameに置き換えてみましょう (元々の結果と同じになっていれば成功です)
以下の通り修正した
cat example_user.rb class User attr_accessor :first_name,:last_name, :email def initialize(attributes = {}) @first_name = attributes[:first_name] @last_name = attributes[:last_name] @email = attributes[:email] end def full_name @full_name = "#{@first_name} #{@last_name}" end def formatted_email "#{@full_name} <#{@email}>" end end
consoleで実行してみます。
?> require './example_user' => true >> user = User.new(first_name: "Michael", last_name: "Hartl", email: "mhartl@example.com") => #<User:0x007fe7bccc0b40 @first_name="Michael", @last_name="Hartl", @email="mhartl@example.com"> >> user.full_name => "Michael Hartl" >> user.formatted_email => "Michael Hartl <mhartl@example.com>"
演習2
"Hartl, Michael" といったフォーマット (苗字と名前がカンマ+半角スペースで区切られている文字列) で返すalphabetical_nameメソッドを定義してみましょう。
演習1で作成したUserクラスを使ってみます。alphabetical_nameを追加です。
$ cat example_user.rb class User attr_accessor :first_name,:last_name, :email def initialize(attributes = {}) @first_name = attributes[:first_name] @last_name = attributes[:last_name] @email = attributes[:email] end def full_name @full_name = "#{@first_name} #{@last_name}" end def alphabetical_name @alphabetical_name = "#{@last_name}, #{@first_name}" end def formatted_email "#{@full_name} <#{@email}>" end end
そしてconsoleで実行してみます。
?> require './example_user' => true >> user = User.new(first_name: "Michael", last_name: "Hartl", email: "mhartl@example.com") => #<User:0x007fe7ba796180 @first_name="Michael", @last_name="Hartl", @email="mhartl@example.com"> >> user.alphabetical_name => "Hartl, Michael"
演習3
full_name.splitとalphabetical_name.split(', ').reverseの結果を比較し、同じ結果になるかどうか確認してみましょう。
以下の通り実施して同じ結果になっていることを確認しました。
>> user.full_name.split => ["Michael", "Hartl"] >> user.alphabetical_name.split(', ').reverse => ["Michael", "Hartl"]
演習までしっかりやってブログ書くとなかなか長かったですね。。。とりあえず4章はこれで終わりです!!
今度は5章やります!!では^^