aboutsummaryrefslogtreecommitdiffstats
path: root/guides/source/active_support_core_extensions.md
diff options
context:
space:
mode:
authorVijay Dev <vijaydev.cse@gmail.com>2012-10-21 18:49:19 +0530
committerVijay Dev <vijaydev.cse@gmail.com>2012-10-21 18:49:19 +0530
commitf938019da210ea2bfccabdf61424852e8006c741 (patch)
tree7cd316340f230efe5b2d55b7df5a85232e5d5db5 /guides/source/active_support_core_extensions.md
parentcec66e589f69a10ab9d6e4b62dd34ff09e5dc01b (diff)
parente84281398e79e09b637c888860fcefd6f82bf968 (diff)
downloadrails-f938019da210ea2bfccabdf61424852e8006c741.tar.gz
rails-f938019da210ea2bfccabdf61424852e8006c741.tar.bz2
rails-f938019da210ea2bfccabdf61424852e8006c741.zip
Merge branch 'master' of github.com:lifo/docrails
Conflicts: activesupport/lib/active_support/core_ext/hash/slice.rb guides/source/active_support_core_extensions.md
Diffstat (limited to 'guides/source/active_support_core_extensions.md')
-rw-r--r--guides/source/active_support_core_extensions.md228
1 files changed, 114 insertions, 114 deletions
diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md
index f990b4f79f..c08ad1ee90 100644
--- a/guides/source/active_support_core_extensions.md
+++ b/guides/source/active_support_core_extensions.md
@@ -358,13 +358,13 @@ Arrays return the result of applying `to_query` to each element with `_key_[]` a
Hashes also respond to `to_query` but with a different signature. If no argument is passed a call generates a sorted series of key/value assignments calling `to_query(key)` on its values. Then it joins the result with "&":
```ruby
-{:c => 3, :b => 2, :a => 1}.to_query # => "a=1&b=2&c=3"
+{c: 3, b: 2, a: 1}.to_query # => "a=1&b=2&c=3"
```
The method `Hash#to_query` accepts an optional namespace for the keys:
```ruby
-{:id => 89, :name => "John Smith"}.to_query('user')
+{id: 89, name: "John Smith"}.to_query('user')
# => "user%5Bid%5D=89&user%5Bname%5D=John+Smith"
```
@@ -378,10 +378,10 @@ Given a default options hash, `with_options` yields a proxy object to a block. W
```ruby
class Account < ActiveRecord::Base
- has_many :customers, :dependent => :destroy
- has_many :products, :dependent => :destroy
- has_many :invoices, :dependent => :destroy
- has_many :expenses, :dependent => :destroy
+ has_many :customers, dependent: :destroy
+ has_many :products, dependent: :destroy
+ has_many :invoices, dependent: :destroy
+ has_many :expenses, dependent: :destroy
end
```
@@ -389,7 +389,7 @@ this way:
```ruby
class Account < ActiveRecord::Base
- with_options :dependent => :destroy do |assoc|
+ with_options dependent: :destroy do |assoc|
assoc.has_many :customers
assoc.has_many :products
assoc.has_many :invoices
@@ -401,9 +401,9 @@ end
That idiom may convey _grouping_ to the reader as well. For example, say you want to send a newsletter whose language depends on the user. Somewhere in the mailer you could group locale-dependent bits like this:
```ruby
-I18n.with_options :locale => user.locale, :scope => "newsletter" do |i18n|
+I18n.with_options locale: user.locale, scope: "newsletter" do |i18n|
subject i18n.t :subject
- body i18n.t :body, :user_name => user.name
+ body i18n.t :body, user_name: user.name
end
```
@@ -892,7 +892,7 @@ That is what `delegate` does for you:
class User < ActiveRecord::Base
has_one :profile
- delegate :name, :to => :profile
+ delegate :name, to: :profile
end
```
@@ -903,17 +903,17 @@ The method must be public in the target.
The `delegate` macro accepts several methods:
```ruby
-delegate :name, :age, :address, :twitter, :to => :profile
+delegate :name, :age, :address, :twitter, to: :profile
```
When interpolated into a string, the `:to` option should become an expression that evaluates to the object the method is delegated to. Typically a string or symbol. Such an expression is evaluated in the context of the receiver:
```ruby
# delegates to the Rails constant
-delegate :logger, :to => :Rails
+delegate :logger, to: :Rails
# delegates to the receiver's class
-delegate :table_name, :to => 'self.class'
+delegate :table_name, to: 'self.class'
```
WARNING: If the `:prefix` option is `true` this is less generic, see below.
@@ -921,7 +921,7 @@ WARNING: If the `:prefix` option is `true` this is less generic, see below.
By default, if the delegation raises `NoMethodError` and the target is `nil` the exception is propagated. You can ask that `nil` is returned instead with the `:allow_nil` option:
```ruby
-delegate :name, :to => :profile, :allow_nil => true
+delegate :name, to: :profile, allow_nil: true
```
With `:allow_nil` the call `user.name` returns `nil` if the user has no profile.
@@ -929,7 +929,7 @@ With `:allow_nil` the call `user.name` returns `nil` if the user has no profile.
The option `:prefix` adds a prefix to the name of the generated method. This may be handy for example to get a better name:
```ruby
-delegate :street, :to => :address, :prefix => true
+delegate :street, to: :address, prefix: true
```
The previous example generates `address_street` rather than `street`.
@@ -939,7 +939,7 @@ WARNING: Since in this case the name of the generated method is composed of the
A custom prefix may also be configured:
```ruby
-delegate :size, :to => :attachment, :prefix => :avatar
+delegate :size, to: :attachment, prefix: :avatar
```
In the previous example the macro generates `avatar_size` rather than `size`.
@@ -1003,10 +1003,10 @@ For example `ActionMailer::Base` defines:
```ruby
class_attribute :default_params
self.default_params = {
- :mime_version => "1.0",
- :charset => "UTF-8",
- :content_type => "text/plain",
- :parts_order => [ "text/plain", "text/enriched", "text/html" ]
+ mime_version: "1.0",
+ charset: "UTF-8",
+ content_type: "text/plain",
+ parts_order: [ "text/plain", "text/enriched", "text/html" ]
}.freeze
```
@@ -1028,7 +1028,7 @@ The generation of the writer instance method can be prevented by setting the opt
```ruby
module ActiveRecord
class Base
- class_attribute :table_name_prefix, :instance_writer => false
+ class_attribute :table_name_prefix, instance_writer: false
self.table_name_prefix = ""
end
end
@@ -1040,7 +1040,7 @@ The generation of the reader instance method can be prevented by setting the opt
```ruby
class A
- class_attribute :x, :instance_reader => false
+ class_attribute :x, instance_reader: false
end
A.new.x = 1 # NoMethodError
@@ -1083,11 +1083,11 @@ The generation of the reader instance method can be prevented by setting `:insta
module A
class B
# No first_name instance reader is generated.
- cattr_accessor :first_name, :instance_reader => false
+ cattr_accessor :first_name, instance_reader: false
# No last_name= instance writer is generated.
- cattr_accessor :last_name, :instance_writer => false
+ cattr_accessor :last_name, instance_writer: false
# No surname instance reader or surname= writer is generated.
- cattr_accessor :surname, :instance_accessor => false
+ cattr_accessor :surname, instance_accessor: false
end
end
```
@@ -1260,7 +1260,7 @@ The method `truncate` returns a copy of its receiver truncated after a given `le
Ellipsis can be customized with the `:omission` option:
```ruby
-"Oh dear! Oh dear! I shall be late!".truncate(20, :omission => '&hellip;')
+"Oh dear! Oh dear! I shall be late!".truncate(20, omission: '&hellip;')
# => "Oh dear! Oh &hellip;"
```
@@ -1271,14 +1271,14 @@ Pass a `:separator` to truncate the string at a natural break:
```ruby
"Oh dear! Oh dear! I shall be late!".truncate(18)
# => "Oh dear! Oh dea..."
-"Oh dear! Oh dear! I shall be late!".truncate(18, :separator => ' ')
+"Oh dear! Oh dear! I shall be late!".truncate(18, separator: ' ')
# => "Oh dear! Oh..."
```
The option `:separator` can be a regexp:
```ruby
-"Oh dear! Oh dear! I shall be late!".truncate(18, :separator => /\s/)
+"Oh dear! Oh dear! I shall be late!".truncate(18, separator: /\s/)
# => "Oh dear! Oh..."
```
@@ -1757,7 +1757,7 @@ def full_messages
each do |attribute, messages|
...
attr_name = attribute.to_s.gsub('.', '_').humanize
- attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
+ attr_name = @base.class.human_attribute_name(attribute, default: attr_name)
...
end
@@ -1861,13 +1861,13 @@ These methods use Time#advance for precise date calculations when using from_now
as well as adding or subtracting their results from a Time object. For example:
```ruby
-# equivalent to Time.current.advance(:months => 1)
+# equivalent to Time.current.advance(months: 1)
1.month.from_now
-# equivalent to Time.current.advance(:years => 2)
+# equivalent to Time.current.advance(years: 2)
2.years.from_now
-# equivalent to Time.current.advance(:months => 4, :years => 5)
+# equivalent to Time.current.advance(months: 4, years: 5)
(4.months + 5.years).from_now
```
@@ -1900,13 +1900,13 @@ Produce a string representation of a number as a telephone number:
# => 555-1234
1235551234.to_s(:phone)
# => 123-555-1234
-1235551234.to_s(:phone, :area_code => true)
+1235551234.to_s(:phone, area_code: true)
# => (123) 555-1234
-1235551234.to_s(:phone, :delimiter => " ")
+1235551234.to_s(:phone, delimiter: " ")
# => 123 555 1234
-1235551234.to_s(:phone, :area_code => true, :extension => 555)
+1235551234.to_s(:phone, area_code: true, extension: 555)
# => (123) 555-1234 x 555
-1235551234.to_s(:phone, :country_code => 1)
+1235551234.to_s(:phone, country_code: 1)
# => +1-123-555-1234
```
@@ -1915,7 +1915,7 @@ Produce a string representation of a number as currency:
```ruby
1234567890.50.to_s(:currency) # => $1,234,567,890.50
1234567890.506.to_s(:currency) # => $1,234,567,890.51
-1234567890.506.to_s(:currency, :precision => 3) # => $1,234,567,890.506
+1234567890.506.to_s(:currency, precision: 3) # => $1,234,567,890.506
```
Produce a string representation of a number as a percentage:
@@ -1923,11 +1923,11 @@ Produce a string representation of a number as a percentage:
```ruby
100.to_s(:percentage)
# => 100.000%
-100.to_s(:percentage, :precision => 0)
+100.to_s(:percentage, precision: 0)
# => 100%
-1000.to_s(:percentage, :delimiter => '.', :separator => ',')
+1000.to_s(:percentage, delimiter: '.', separator: ',')
# => 1.000,000%
-302.24398923423.to_s(:percentage, :precision => 5)
+302.24398923423.to_s(:percentage, precision: 5)
# => 302.24399%
```
@@ -1936,19 +1936,19 @@ Produce a string representation of a number in delimited form:
```ruby
12345678.to_s(:delimited) # => 12,345,678
12345678.05.to_s(:delimited) # => 12,345,678.05
-12345678.to_s(:delimited, :delimiter => ".") # => 12.345.678
-12345678.to_s(:delimited, :delimiter => ",") # => 12,345,678
-12345678.05.to_s(:delimited, :separator => " ") # => 12,345,678 05
+12345678.to_s(:delimited, delimiter: ".") # => 12.345.678
+12345678.to_s(:delimited, delimiter: ",") # => 12,345,678
+12345678.05.to_s(:delimited, separator: " ") # => 12,345,678 05
```
Produce a string representation of a number rounded to a precision:
```ruby
111.2345.to_s(:rounded) # => 111.235
-111.2345.to_s(:rounded, :precision => 2) # => 111.23
-13.to_s(:rounded, :precision => 5) # => 13.00000
-389.32314.to_s(:rounded, :precision => 0) # => 389
-111.2345.to_s(:rounded, :significant => true) # => 111
+111.2345.to_s(:rounded, precision: 2) # => 111.23
+13.to_s(:rounded, precision: 5) # => 13.00000
+389.32314.to_s(:rounded, precision: 0) # => 389
+111.2345.to_s(:rounded, significant: true) # => 111
```
Produce a string representation of a number as a human-readable number of bytes:
@@ -2042,7 +2042,7 @@ Addition only assumes the elements respond to `+`:
```ruby
[[1, 2], [2, 3], [3, 4]].sum # => [1, 2, 2, 3, 3, 4]
%w(foo bar baz).sum # => "foobarbaz"
-{:a => 1, :b => 2, :c => 3}.sum # => [:b, 2, :c, 3, :a, 1]
+{a: 1, b: 2, c: 3}.sum # => [:b, 2, :c, 3, :a, 1]
```
The sum of an empty collection is zero by default, but this is customizable:
@@ -2176,7 +2176,7 @@ NOTE: Defined in `active_support/core_ext/array/prepend_and_append.rb`.
When the last argument in a method call is a hash, except perhaps for a `&block` argument, Ruby allows you to omit the brackets:
```ruby
-User.exists?(:email => params[:email])
+User.exists?(email: params[:email])
```
That syntactic sugar is used a lot in Rails to avoid positional arguments where there would be too many, offering instead interfaces that emulate named parameters. In particular it is very idiomatic to use a trailing hash for options.
@@ -2305,7 +2305,7 @@ If there's any element that does not belong to the type of the first one the roo
If the receiver is an array of hashes the root element is by default also "objects":
```ruby
-[{:a => 1, :b => 2}, {:c => 3}].to_xml
+[{a: 1, b: 2}, {c: 3}].to_xml
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <objects type="array">
@@ -2326,7 +2326,7 @@ The name of children nodes is by default the name of the root node singularized.
The default XML builder is a fresh instance of `Builder::XmlMarkup`. You can configure your own builder via the `:builder` option. The method also accepts options like `:dasherize` and friends, they are forwarded to the builder:
```ruby
-Contributor.limit(2).order(:rank).to_xml(:skip_types => true)
+Contributor.limit(2).order(:rank).to_xml(skip_types: true)
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <contributors>
@@ -2372,8 +2372,8 @@ This method is similar in purpose to `Kernel#Array`, but there are some differen
The last point is particularly worth comparing for some enumerables:
```ruby
-Array.wrap(:foo => :bar) # => [{:foo => :bar}]
-Array(:foo => :bar) # => [[:foo, :bar]]
+Array.wrap(foo: :bar) # => [{foo: :bar}]
+Array(foo: :bar) # => [[:foo, :bar]]
```
There's also a related idiom that uses the splat operator:
@@ -2556,8 +2556,8 @@ NOTE: Defined in `active_support/core_ext/hash/conversions.rb`.
Ruby has a built-in method `Hash#merge` that merges two hashes:
```ruby
-{:a => 1, :b => 1}.merge(:a => 0, :c => 2)
-# => {:a => 0, :b => 1, :c => 2}
+{a: 1, b: 1}.merge(a: 0, c: 2)
+# => {a: 0, b: 1, c: 2}
```
Active Support defines a few more ways of merging hashes that may be convenient.
@@ -2567,19 +2567,19 @@ Active Support defines a few more ways of merging hashes that may be convenient.
In case of collision the key in the hash of the argument wins in `merge`. You can support option hashes with default values in a compact way with this idiom:
```ruby
-options = {:length => 30, :omission => "..."}.merge(options)
+options = {length: 30, omission: "..."}.merge(options)
```
Active Support defines `reverse_merge` in case you prefer this alternative notation:
```ruby
-options = options.reverse_merge(:length => 30, :omission => "...")
+options = options.reverse_merge(length: 30, omission: "...")
```
And a bang version `reverse_merge!` that performs the merge in place:
```ruby
-options.reverse_merge!(:length => 30, :omission => "...")
+options.reverse_merge!(length: 30, omission: "...")
```
WARNING. Take into account that `reverse_merge!` may change the hash in the caller, which may or may not be a good idea.
@@ -2601,8 +2601,8 @@ As you can see in the previous example if a key is found in both hashes the valu
Active Support defines `Hash#deep_merge`. In a deep merge, if a key is found in both hashes and their values are hashes in turn, then their _merge_ becomes the value in the resulting hash:
```ruby
-{:a => {:b => 1}}.deep_merge(:a => {:c => 2})
-# => {:a => {:b => 1, :c => 2}}
+{a: {b: 1}}.deep_merge(a: {c: 2})
+# => {a: {b: 1, c: 2}}
```
The method `deep_merge!` performs a deep merge in place.
@@ -2614,7 +2614,7 @@ NOTE: Defined in `active_support/core_ext/hash/deep_merge.rb`.
The method `Hash.deep_dup` duplicates itself and all keys and values inside recursively with ActiveSupport method `Object#deep_dup`. It works like `Enumerator#each_with_object` with sending `deep_dup` method to each pair inside.
```ruby
-hash = { :a => 1, :b => { :c => 2, :d => [3, 4] } }
+hash = { a: 1, b: { c: 2, d: [3, 4] } }
dup = hash.deep_dup
dup[:b][:e] = 5
@@ -2637,21 +2637,21 @@ The method `diff` returns a hash that represents a diff of the receiver and the
* The rest is just merged.
```ruby
-{:a => 1}.diff(:a => 1)
+{a: 1}.diff(a: 1)
# => {}, first rule
-{:a => 1}.diff(:a => 2)
-# => {:a => 1}, second rule
+{a: 1}.diff(a: 2)
+# => {a: 1}, second rule
-{:a => 1}.diff(:b => 2)
-# => {:a => 1, :b => 2}, third rule
+{a: 1}.diff(b: 2)
+# => {a: 1, b: 2}, third rule
-{:a => 1, :b => 2, :c => 3}.diff(:b => 1, :c => 3, :d => 4)
-# => {:a => 1, :b => 2, :d => 4}, all rules
+{a: 1, b: 2, c: 3}.diff(b: 1, c: 3, d: 4)
+# => {a: 1, b: 2, d: 4}, all rules
{}.diff({}) # => {}
-{:a => 1}.diff({}) # => {:a => 1}
-{}.diff(:a => 1) # => {:a => 1}
+{a: 1}.diff({}) # => {a: 1}
+{}.diff(a: 1) # => {a: 1}
```
An important property of this diff hash is that you can retrieve the original hash by applying `diff` twice:
@@ -2671,14 +2671,14 @@ NOTE: Defined in `active_support/core_ext/hash/diff.rb`.
The method `except` returns a hash with the keys in the argument list removed, if present:
```ruby
-{:a => 1, :b => 2}.except(:a) # => {:b => 2}
+{a: 1, b: 2}.except(:a) # => {b: 2}
```
If the receiver responds to `convert_key`, the method is called on each of the arguments. This allows `except` to play nice with hashes with indifferent access for instance:
```ruby
-{:a => 1}.with_indifferent_access.except(:a) # => {}
-{:a => 1}.with_indifferent_access.except("a") # => {}
+{a: 1}.with_indifferent_access.except(:a) # => {}
+{a: 1}.with_indifferent_access.except("a") # => {}
```
The method `except` may come in handy for example when you want to protect some parameter that can't be globally protected with `attr_protected`:
@@ -2697,14 +2697,14 @@ NOTE: Defined in `active_support/core_ext/hash/except.rb`.
The method `transform_keys` accepts a block and returns a hash that has applied the block operations to each of the keys in the receiver:
```ruby
-{nil => nil, 1 => 1, :a => :a}.transform_keys{ |key| key.to_s.upcase }
+{nil => nil, 1 => 1, a: :a}.transform_keys{ |key| key.to_s.upcase }
# => {"" => nil, "A" => :a, "1" => 1}
```
The result in case of collision is undefined:
```ruby
-{"a" => 1, :a => 2}.transform_keys{ |key| key.to_s.upcase }
+{"a" => 1, a: 2}.transform_keys{ |key| key.to_s.upcase }
# => {"A" => 2}, in my test, can't rely on this result though
```
@@ -2725,7 +2725,7 @@ There's also the bang variant `transform_keys!` that applies the block operation
Besides that, one can use `deep_transform_keys` and `deep_transform_keys!` to perform the block operation on all the keys in the given hash and all the hashes nested into it. An example of the result is:
```ruby
-{nil => nil, 1 => 1, :nested => {:a => 3, 5 => 5}}.deep_transform_keys{ |key| key.to_s.upcase }
+{nil => nil, 1 => 1, nested: {a: 3, 5 => 5}}.deep_transform_keys{ |key| key.to_s.upcase }
# => {""=>nil, "1"=>1, "NESTED"=>{"A"=>3, "5"=>5}}
```
@@ -2736,14 +2736,14 @@ NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
The method `stringify_keys` returns a hash that has a stringified version of the keys in the receiver. It does so by sending `to_s` to them:
```ruby
-{nil => nil, 1 => 1, :a => :a}.stringify_keys
+{nil => nil, 1 => 1, a: :a}.stringify_keys
# => {"" => nil, "a" => :a, "1" => 1}
```
The result in case of collision is undefined:
```ruby
-{"a" => 1, :a => 2}.stringify_keys
+{"a" => 1, a: 2}.stringify_keys
# => {"a" => 2}, in my test, can't rely on this result though
```
@@ -2764,7 +2764,7 @@ There's also the bang variant `stringify_keys!` that stringifies keys in the ver
Besides that, one can use `deep_stringify_keys` and `deep_stringify_keys!` to stringify all the keys in the given hash and all the hashes nested into it. An example of the result is:
```ruby
-{nil => nil, 1 => 1, :nested => {:a => 3, 5 => 5}}.deep_stringify_keys
+{nil => nil, 1 => 1, nested: {a: 3, 5 => 5}}.deep_stringify_keys
# => {""=>nil, "1"=>1, "nested"=>{"a"=>3, "5"=>5}}
```
@@ -2776,7 +2776,7 @@ The method `symbolize_keys` returns a hash that has a symbolized version of the
```ruby
{nil => nil, 1 => 1, "a" => "a"}.symbolize_keys
-# => {1 => 1, nil => nil, :a => "a"}
+# => {1 => 1, nil => nil, a: "a"}
```
WARNING. Note in the previous example only one key was symbolized.
@@ -2784,8 +2784,8 @@ WARNING. Note in the previous example only one key was symbolized.
The result in case of collision is undefined:
```ruby
-{"a" => 1, :a => 2}.symbolize_keys
-# => {:a => 2}, in my test, can't rely on this result though
+{"a" => 1, a: 2}.symbolize_keys
+# => {a: 2}, in my test, can't rely on this result though
```
This method may be useful for example to easily accept both symbols and strings as options. For instance `ActionController::UrlRewriter` defines
@@ -2806,7 +2806,7 @@ Besides that, one can use `deep_symbolize_keys` and `deep_symbolize_keys!` to sy
```ruby
{nil => nil, 1 => 1, "nested" => {"a" => 3, 5 => 5}}.deep_symbolize_keys
-# => {nil=>nil, 1=>1, :nested=>{:a=>3, 5=>5}}
+# => {nil=>nil, 1=>1, nested:{a:3, 5=>5}}
```
NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
@@ -2822,8 +2822,8 @@ NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
The method `assert_valid_keys` receives an arbitrary number of arguments, and checks whether the receiver has any key outside that white list. If it does `ArgumentError` is raised.
```ruby
-{:a => 1}.assert_valid_keys(:a) # passes
-{:a => 1}.assert_valid_keys("a") # ArgumentError
+{a: 1}.assert_valid_keys(:a) # passes
+{a: 1}.assert_valid_keys("a") # ArgumentError
```
Active Record does not accept unknown options when building associations, for example. It implements that control via `assert_valid_keys`.
@@ -2835,18 +2835,18 @@ NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
Ruby has built-in support for taking slices out of strings and arrays. Active Support extends slicing to hashes:
```ruby
-{:a => 1, :b => 2, :c => 3}.slice(:a, :c)
-# => {:c => 3, :a => 1}
+{a: 1, b: 2, c: 3}.slice(:a, :c)
+# => {c: 3, a: 1}
-{:a => 1, :b => 2, :c => 3}.slice(:b, :X)
-# => {:b => 2} # non-existing keys are ignored
+{a: 1, b: 2, c: 3}.slice(:b, :X)
+# => {b: 2} # non-existing keys are ignored
```
If the receiver responds to `convert_key` keys are normalized:
```ruby
-{:a => 1, :b => 2}.with_indifferent_access.slice("a")
-# => {:a => 1}
+{a: 1, b: 2}.with_indifferent_access.slice("a")
+# => {a: 1}
```
NOTE. Slicing may come in handy for sanitizing option hashes with a white list of keys.
@@ -2854,9 +2854,9 @@ NOTE. Slicing may come in handy for sanitizing option hashes with a white list o
There's also `slice!` which in addition to perform a slice in place returns what's removed:
```ruby
-hash = {:a => 1, :b => 2}
-rest = hash.slice!(:a) # => {:b => 2}
-hash # => {:a => 1}
+hash = {a: 1, b: 2}
+rest = hash.slice!(:a) # => {b: 2}
+hash # => {a: 1}
```
NOTE: Defined in `active_support/core_ext/hash/slice.rb`.
@@ -2866,15 +2866,15 @@ NOTE: Defined in `active_support/core_ext/hash/slice.rb`.
The method `extract!` removes and returns the key/value pairs matching the given keys.
```ruby
-hash = {:a => 1, :b => 2}
-rest = hash.extract!(:a, :x) # => {:a => 1} # non-existing keys are ignored
-hash # => {:b => 2}
+hash = {a: 1, b: 2}
+rest = hash.extract!(:a) # => {a: 1}
+hash # => {b: 2}
```
The method `extract!` returns the same subclass of Hash, that the receiver is.
```ruby
-hash = {:a => 1, :b => 2}.with_indifferent_access
+hash = {a: 1, b: 2}.with_indifferent_access
rest = hash.extract!(:a).class
# => ActiveSupport::HashWithIndifferentAccess
```
@@ -2886,7 +2886,7 @@ NOTE: Defined in `active_support/core_ext/hash/slice.rb`.
The method `with_indifferent_access` returns an `ActiveSupport::HashWithIndifferentAccess` out of its receiver:
```ruby
-{:a => 1}.with_indifferent_access["a"] # => 1
+{a: 1}.with_indifferent_access["a"] # => 1
```
NOTE: Defined in `active_support/core_ext/hash/indifferent_access.rb`.
@@ -2990,7 +2990,7 @@ An unbound method is not callable as is, you need to bind it first to an object
```ruby
clear = Hash.instance_method(:clear)
-clear.bind({:a => 1}).call # => {}
+clear.bind({a: 1}).call # => {}
```
Active Support defines `Proc#bind` with an analogous purpose:
@@ -3249,8 +3249,8 @@ The most generic way to jump to other days is `advance`. This method receives a
```ruby
date = Date.new(2010, 6, 6)
-date.advance(:years => 1, :weeks => 2) # => Mon, 20 Jun 2011
-date.advance(:months => 2, :days => -2) # => Wed, 04 Aug 2010
+date.advance(years: 1, weeks: 2) # => Mon, 20 Jun 2011
+date.advance(months: 2, days: -2) # => Wed, 04 Aug 2010
```
Note in the previous example that increments may be negative.
@@ -3260,14 +3260,14 @@ To perform the computation the method first increments years, then months, then
The method `advance` advances first one month, and then one day, the result is:
```ruby
-Date.new(2010, 2, 28).advance(:months => 1, :days => 1)
+Date.new(2010, 2, 28).advance(months: 1, days: 1)
# => Sun, 29 Mar 2010
```
While if it did it the other way around the result would be different:
```ruby
-Date.new(2010, 2, 28).advance(:days => 1).advance(:months => 1)
+Date.new(2010, 2, 28).advance(days: 1).advance(months: 1)
# => Thu, 01 Apr 2010
```
@@ -3276,14 +3276,14 @@ Date.new(2010, 2, 28).advance(:days => 1).advance(:months => 1)
The method `change` allows you to get a new date which is the same as the receiver except for the given year, month, or day:
```ruby
-Date.new(2010, 12, 23).change(:year => 2011, :month => 11)
+Date.new(2010, 12, 23).change(year: 2011, month: 11)
# => Wed, 23 Nov 2011
```
This method is not tolerant to non-existing dates, if the change is invalid `ArgumentError` is raised:
```ruby
-Date.new(2010, 1, 31).change(:month => 2)
+Date.new(2010, 1, 31).change(month: 2)
# => ArgumentError: invalid date
```
@@ -3469,7 +3469,7 @@ The most generic way to jump to another datetime is `advance`. This method recei
```ruby
d = DateTime.current
# => Thu, 05 Aug 2010 11:33:31 +0000
-d.advance(:years => 1, :months => 1, :days => 1, :hours => 1, :minutes => 1, :seconds => 1)
+d.advance(years: 1, months: 1, days: 1, hours: 1, minutes: 1, seconds: 1)
# => Tue, 06 Sep 2011 12:34:32 +0000
```
@@ -3480,14 +3480,14 @@ If we first move the date bits (that have also a relative order of processing, a
```ruby
d = DateTime.new(2010, 2, 28, 23, 59, 59)
# => Sun, 28 Feb 2010 23:59:59 +0000
-d.advance(:months => 1, :seconds => 1)
+d.advance(months: 1, seconds: 1)
# => Mon, 29 Mar 2010 00:00:00 +0000
```
but if we computed them the other way around, the result would be different:
```ruby
-d.advance(:seconds => 1).advance(:months => 1)
+d.advance(seconds: 1).advance(months: 1)
# => Thu, 01 Apr 2010 00:00:00 +0000
```
@@ -3500,28 +3500,28 @@ The method `change` allows you to get a new datetime which is the same as the re
```ruby
now = DateTime.current
# => Tue, 08 Jun 2010 01:56:22 +0000
-now.change(:year => 2011, :offset => Rational(-6, 24))
+now.change(year: 2011, offset: Rational(-6, 24))
# => Wed, 08 Jun 2011 01:56:22 -0600
```
If hours are zeroed, then minutes and seconds are too (unless they have given values):
```ruby
-now.change(:hour => 0)
+now.change(hour: 0)
# => Tue, 08 Jun 2010 00:00:00 +0000
```
Similarly, if minutes are zeroed, then seconds are too (unless it has given a value):
```ruby
-now.change(:min => 0)
+now.change(min: 0)
# => Tue, 08 Jun 2010 01:00:00 +0000
```
This method is not tolerant to non-existing dates, if the change is invalid `ArgumentError` is raised:
```ruby
-DateTime.current.change(:month => 2, :day => 30)
+DateTime.current.change(month: 2, day: 30)
# => ArgumentError: invalid date
```
@@ -3604,7 +3604,7 @@ Time.zone_default
# In Barcelona, 2010/03/28 02:00 +0100 becomes 2010/03/28 03:00 +0200 due to DST.
t = Time.local_time(2010, 3, 28, 1, 59, 59)
# => Sun Mar 28 01:59:59 +0100 2010
-t.advance(:seconds => 1)
+t.advance(seconds: 1)
# => Sun Mar 28 03:00:00 +0200 2010
```