Railsで使われているRubyの知識のまとめ

369603 ワード

詳細
1.+2文字列の接続
 
>> "foo" + "bar"    # String concatenation
=> "foobar"

 
2.埋め込み式
 
>> first_name = "Michael"    # Variable assignment
=> "Michael"
>> "#{first_name} Hartl"     # String interpolation
=> "Michael Hartl"

 
3.putsメソッド(put string)
 
>> puts "foo"     # put string
foo
=> nil

 
putsメソッドが文字列の字面量を印刷した後、nilメソッドを返したことがわかります(これは特別なもので、後で分析します).
 
4.putsメソッドでは、行の最後に改行記号が自動的に追加され、printメソッドに対応します.
 
>> print "foo"    # print string (same as puts, but without the newline)
foo=> nil
>> print "foo
" # Same as puts "foo" foo => nil

 
5.一重引用符と二重引用符
 
>> 'foo'          # A single-quoted string
=> "foo"
>> 'foo' + 'bar'
=> "foobar"

 
 
>> '#{foo} bar'     # Single-quoted strings don't allow interpolation
=> "\#{foo} bar"

 
単一引用符は、引用符内の内容を実行することなく、引用符の内容を印刷します.¥,#のような特殊な記号の前にを付けます.
 
6.Rubyは、文字列とnilを含むオブジェクトです.
 
7.lengthメソッド
 
>> "foobar".length        # Passing the "length" message to a string
=> 6

 
8.empty?方法
 
>> "foobar".empty?
=> false
>> "".empty?
=> true

 
9.nilもオブジェクトなので、nilにも方法があります.to_sは文字列に変更できます
 
>> nil.to_s
=> ""

 
10.nil自体はemptyメソッドに応答するのではなくnilである.to_s
 
>> nil.empty?
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.empty?
>> nil.to_s.empty?      # Message chaining
=> true

 
11.nilを検査する方法nil?
 
>> "foo".nil?
=> false
>> "".nil?
=> false
>> nil.nil?
=> true

 
12.nilの方法は前に言ったことがありますが、特に言えば、それは特別にどこにありますか.Rubyではfalseというブール値を除いてfalseであり,nilのみfalseであり,以下の検証により
 
>> if nil
>>   true
>> else
>>   false        # nil is false
>> end
=> false
>> if 0
>>   true        # 0 (and everything other than nil and false itself) is true
>> else
>>   false
>> end
=> true

 
13.12で述べたように、Rubyではfalseとnilを除いてfalseであり、0を含むtrueである.上記のコードで示します.
 
14.Rubyのメソッドの戻りは、デフォルトで最後の文を返します.もちろんreturnで明示的に返しても問題ありません.
 
15.文字列を配列に切断する.spiltメソッド:
デフォルトの使用
 
>>  "foo bar     baz".split     # Split a string into a three-element array
=> ["foo", "bar", "baz"]

 
もちろん、spiltは次のように使用できます.
 
>> "fooxbarxbazx".split('x')
=> ["foo", "bar", "baz"]

 
 
>> "fooxxarxbazx".split('x')
=> ["foo", "","ar", "baz"]

 
16.他の言語のようにRuby配列の開始インデックスは0から始まり、負数は逆数インデックス、-1は最後のインデックスを表す
 
>> a = [42, 8, 17]
=> [42, 8, 17]
>> a[0]               # Ruby uses square brackets for array access.
=> 42
>> a[1]
=> 8
>> a[2]
=> 17
>> a[-1]              # Indices can even be negative!
=> 17

 
17.配列特殊アクセス方法、first、second、last
 
>> a                  # Just a reminder of what 'a' is
=> [42, 8, 17]
>> a.first
=> 42
>> a.second
=> 8
>> a.last
=> 17
>> a.last == a[-1]    # Comparison using ==
=> true

 
18.lengthメソッドに加えて、配列には多くのメソッドがあります.
 
>> a
=> [42, 8, 17]
>> a.sort
=> [8, 17, 42]
>> a.reverse
=> [17, 8, 42]
>> a.shuffle
=> [17, 42, 8]
>> a
=> [42, 8, 17]

19.上の最後の行から分かるように、多くの方法が呼び出されていますが、aの値は変更されていません.どのように変更しますか.
 
>> a
=> [42, 8, 17]
>> a.sort!
=> [8, 17, 42]
>> a
=> [8, 17, 42]

!メソッド(bang)は配列の値を変更することができる.
 
20.配列に要素を挿入する
 
>> a.push(6)                  # Pushing 6 onto an array
=> [42, 8, 17, 6]
>> a << 7                     # Pushing 7 onto an array
=> [42, 8, 17, 6, 7]
>> a << "foo" << "bar"        # Chaining array pushes
=> [42, 8, 17, 6, 7, "foo", "bar"]

push以外にも<
 
21.splitメソッドでは、文字列を配列に分割できますが、配列要素を組み合わせるにはどうすればいいのでしょうか.
 
>> a
=> [42, 8, 17, 7, "foo", "bar"]
>> a.join                       # Join on nothing
=> "428177foobar"
>> a.join(', ')                 # Join on comma-space
=> "42, 8, 17, 7, foo, bar"

joinメソッドは,配列要素がどんなタイプであってもjoinの後は文字列タイプである配列要素を組み合わせることができることがわかる.もちろんjoinも伝参できますが、上記のように.
 
22.rangeおよびto_a方法
 
>> 0..9
=> 0..9
>> 0..9.to_a              # Oops, call to_a on 9
NoMethodError: undefined method `to_a' for 9:Fixnum
>> (0..9).to_a            # Use parentheses to call to_a on the range
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

表示されます..方法はとても便利で、もちろん上述のように、9はto_がありませんaメソッドの、to_aはrange向けです.
 
23.rangeは配列要素を簡単に取り出すことができる
 
>> a = %w[foo bar baz quux]         # Use %w to make a string array.
=> ["foo", "bar", "baz", "quux"]
>> a[0..2]
=> ["foo", "bar", "baz"]

ここで、%w{String}は、1つの文字列を空白文字で1つの文字列配列に分割し、より少ない置換を行うために使用されます.
rangeにはもう一つ、2つのポイントのほかに3つのポイントが...、例えば0...1、0だけ取って、1まで取ってはいけません.
 
24.rangeにはセクシーな使い方があります.
 
>> ('a'..'e').to_a
=> ["a", "b", "c", "d", "e"]

 
25.Rubyの配列とrangeにはblockを受け入れる方法があります.これもrubyの強みで、初心者を惑わすことが多いです.
 
>> (1..5).each { |i| puts 2 * i }
2
4
6
8
10
=> 1..5

 
上記のコードはrange(1..5)に対してeachメソッドを呼び出し、|i|は変数iを表し、このblockはiを変数として実行される.
 
上のコードもこのように書くことができます.
 
>> (1..5).each do |i|
?>   puts 2 * i
>> end
2
4
6
8
10
=> 1..5

 
後者はrailsでよく使われる.
 
26.他の一般的な方法では、%wが迷っています.上で説明しました.もう一度%w{String}を強調します.1つの文字列を空白文字で1つの文字列配列に分割し、置換を少なくします.
 
>> 3.times { puts "Betelgeuse!" }   # 3.times takes a block with no variables.
"Betelgeuse!"
"Betelgeuse!"
"Betelgeuse!"
=> 3
>> (1..5).map { |i| i**2 }          # The ** notation is for 'power'.
=> [1, 4, 9, 16, 25]
>> %w[a b c]                        # Recall that %w makes string arrays.
=> ["a", "b", "c"]
>> %w[a b c].map { |char| char.upcase }
=> ["A", "B", "C"]
>> %w[A B C].map { |char| char.downcase }
=> ["a", "b", "c"]

mapメソッドは、ブロックが適用された配列またはrangeの結果を返します.
 
27.これらの理解の差が少なくなったら、この文を見てみましょう.
 
('a'..'z').to_a.shuffle[0..7].join
すべてのアルファベットからなる配列で、サイズは26で、順序を乱し、最初の8つを取り、文字列に接続します.
を選択し、各ステップを実行して分析できます.
 
>> ('a'..'z').to_a                     # An alphabet array
=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
"p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
>> ('a'..'z').to_a.shuffle             # Shuffle it.
=> ["c", "g", "l", "k", "h", "z", "s", "i", "n", "d", "y", "u", "t", "j", "q",
"b", "r", "o", "f", "e", "w", "v", "m", "a", "x", "p"]
>> ('a'..'z').to_a.shuffle[0..7]       # Pull out the first eight elements.
=> ["f", "w", "i", "a", "h", "p", "c", "x"]
>> ('a'..'z').to_a.shuffle[0..7].join  # Join them together to make one string.
=> "mznpybuj"

 
次はHashとsymbol
 
28.hashは本質的に配列です.keyを整数として扱うとき.もちろん、hashと配列の違いは、hashのkeyが何であっても、オブジェクトであってもよいことにある.
 
>> user = {}                          # {} is an empty hash.
=> {}
>> user["first_name"] = "Michael"     # Key "first_name", value "Michael"
=> "Michael"
>> user["last_name"] = "Hartl"        # Key "last_name", value "Hartl"
=> "Hartl"
>> user["first_name"]                 # Element access is like arrays.
=> "Michael"
>> user                               # A literal representation of the hash
=> {"last_name"=>"Hartl", "first_name"=>"Michael"}

hashのインデックスは、配列に似ていることがわかります.
 
29.hashは一対の括弧で、中にキー値が含まれて名前をつけます.もちろん、キー値が含まれていないものは空hashとなります.ここで明確にするのは、hashのカッコはblockのカッコとは何の関係もありません.
 
>> user = { "first_name" => "Michael", "last_name" => "Hartl" }
=> {"last_name"=>"Hartl", "first_name"=>"Michael"}

ここで、rubyの約束に従い、括弧の両端にスペースを入れます.約束、約束.
 
30、Rubyではstringをkeyとして使用することが多いが、railsではsymbolをキーとして使用することが多い.
 
 
>> "name".split('')
=> ["n", "a", "m", "e"]
>> :name.split('')
NoMethodError: undefined method `split' for :name:Symbol
>> "foobar".reverse
=> "raboof"
>> :foobar.reverse
NoMethodError: undefined method `reverse' for :foobar:Symbol

Symbolは、コンパイル中に変化しない量を表します.私たちはこのように定義することができます.railsですね.
 
>> user = { :name => "Michael Hartl", :email => "[email protected]" }
=> {:name=>"Michael Hartl", :email=>"[email protected]"}
>> user[:name]              # Access the value corresponding to :name.
=> "Michael Hartl"
>> user[:password]          # Access the value of an undefined key.
=> nil

存在しないキーの場合、nilが返されます.ruby1.9以降もこの表現が導入されている.
もちろん、もう一つの表現があります.
 
{ name: "Michael Hartl", email: "[email protected]" }

Ruby1.8.7以降のバージョンはあまりサポートされていません.
 
31.hashの値は何でもいい
 
>> params = {}        # Define a hash called 'params' (short for 'parameters').
=> {}
>> params[:user] = { name: "Michael Hartl", email: "[email protected]" }
=> {:name=>"Michael Hartl", :email=>"[email protected]"}
>> params
=> {:user=>{:name=>"Michael Hartl", :email=>"[email protected]"}}
>>  params[:user][:email]
=> "[email protected]"

上記のようなネストされたhashはrailsでよく見られる.
 
32.arrayやrangeと同様にhashにも対応するeachメソッドがある
 
>> flash = { success: "It worked!", error: "It failed." }
=> {:success=>"It worked!", :error=>"It failed."}
>> flash.each do |key, value|
?>   puts "Key #{key.inspect} has value #{value.inspect}"
>> end
Key :success has value "It worked!"
Key :error has value "It failed."

 
配列のeachメソッドのblockは変数を受け入れ,hashのblockは2つのパラメータ(キー値対)を必要とすることに留意されたい.
 
33.次に、呼び出しオブジェクトの文字列の直角値を返し、抽象的な方法inspectがあります.
>> puts (1..5).to_a            # Put an array as a string.
1
2
3
4
5
>> puts (1..5).to_a.inspect    # Put a literal array.
[1, 2, 3, 4, 5]
>> puts :name, :name.inspect
name
:name
>> puts "It worked!", "It worked!".inspect
It worked!
"It worked!"

 
Inspectとpの意味の差は多くありませんが、実は、pの方法はinspectの略です.
 
>> p :name             # Same as 'puts :name.inspect'
:name

 
34.約束!!約束!
Rubyのメソッドパラメータのかっこは、省略できます.
 
# Parentheses on function calls are optional.
stylesheet_link_tag("application", :media => "all")
stylesheet_link_tag "application", :media => "all"

 
railsではhashが最後のパラメータであれば括弧も省略できますが、
 
# Curly braces on final hash arguments are optional.
stylesheet_link_tag "application", { :media => "all" }
stylesheet_link_tag "application", :media => "all"

 
 
次に、rubyのクラスのまとめです
35.classでインスタンス化されたオブジェクトも多く見られ、明示的にそうしています.たとえば、stringをインスタンス化し、二重引用符を使用します.これはstringの字面量構造です.
>> s = "foobar"       # A literal constructor for strings using double quotes
=> "foobar"
>> s.class
=> String

それ以外にnewで明示的に構築できます
 
>> s = String.new("foobar")   # A named constructor for a string
=> "foobar"
>> s.class
=> String
>> s == "foobar"
=> true

 
配列は文字列に似ています
 
 
>> a = Array.new([1, 3, 2])
=> [1, 3, 2]

 
hashは少し異なり、配列構造の場合は初期値を指定する必要があり、hashにはデフォルトの初期値があります.
 
>> h = Hash.new
=> {}
>> h[:foo]            # Try to access the value for the nonexistent key :foo.
=> nil
>> h = Hash.new(0)    # Arrange for nonexistent keys to return 0 instead of nil.
=> {}
>> h[:foo]
=> 0

 
36.クラスの継承は、classメソッドで現在のインスタンスのクラスを得ることができ、superclassでその親クラスを得ることができます.の
 
>> s = String.new("foobar")
=> "foobar"
>> s.class                        # Find the class of s.
=> String
>> s.class.superclass             # Find the superclass of String.
=> Object
>> s.class.superclass.superclass  # Ruby 1.9 uses a new BasicObject base class
=> BasicObject 
>> s.class.superclass.superclass.superclass
=> nil

 
37.継承問題を説明するために、このような例を見て、回文であるか否かを判断する.
 
>> class Word
>>   def palindrome?(string)
>>     string == string.reverse
>>   end
>> end
=> nil
>> w = Word.new              # Make a new Word object.
=> #<0x22d0b20/>
>> w.palindrome?("foobar")
=> false
>> w.palindrome?("level")
=> true

 
次の方法を見てみましょう
 
>> class Word < String             # Word inherits from String.
>>   # Returns true if the string is its own reverse.
>>   def palindrome?
>>     self == self.reverse        # self is the string itself.
>>   end
>> end
=> nil

 
 
>> s.class
=> Word
>> s.class.superclass
=> String
>> s.class.superclass.superclass
=> Object

 
継承の過程が明らかに見えます
 
 
38.組み込みクラスの変更方法
 
>> "level".palindrome?
NoMethodError: undefined method `palindrome?' for "level":String
>> class String
>>   # Returns true if the string is its own reverse.
>>   def palindrome?
>>     self == self.reverse
>>   end
>> end
=> nil
>> "deified".palindrome?
=> true

 
39.上記の方法は良し悪しがあるが、railsでは実用的である.
Web開発では変数が空になるのを阻止することが多いため、例えばuser nameは空白文字以外の文字でなければならないため、blankを実現しましたか?方法
 
>> "".blank?
=> true
>> "      ".empty?
=> false
>> "      ".blank?
=> true
>> nil.blank?
=> true

 
40 railsのuserクラスを分析する
 
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

 
新しいプロパティのaccessorはnameとemailに対応し、getterとsetterメソッドが新しく作成され、インスタンス変数@name,@emalと付与値を取得できます.Railsのインスタンス変数の重要性は、viewsで自動的に表示されることです.
 
そしてまた見に来ます
 
  def initialize(attributes = {})
 
    @name  = attributes[:name]
    @email = attributes[:email]
  end

 
InitializeメソッドはRubyでは特別です.Userを実行すると.newの場合、呼び出されます.パラメータがあります.ここでattrbutes変数のデフォルト値は空のhashであるため、nameまたはemailがない場合、hashはnilを返します.したがって、nameというキーがない場合attributes[:name]はnilです.
 
最後に、このクラスはformmatedという名前を定義しました.Emailの方法では、埋め込み式を使用してemailアドレスを作成します.
 
  def formatted_email
    "#{@name} <#{@email}>"
  end

@nameと@emailはインスタンス変数なのでformatted_Emailメソッドで表示されます.