The collection Authoring Guide in Ruby _ruby topics

Source: Internet
Author: User
Tags arrays

tend to the literal notation of arrays and hashes (unless you need to pass arguments to their constructors).

  # bad
  arr = array.new
  hash = hash.new

  # good
  arr = []
  hash = {}

You always use%w to define an array of strings when you need an array of elements that are words (without spaces and special symbols). Apply this rule only in two or more arrays.

  # bad
  STATES = [' Draft ', ' Open ', ' closed ']

  # good
  STATES =%w (draft open closed)

Use%i when you need an array of symbols (and do not need to maintain Ruby 1.9 compatibility). This rule is applied only if the array has only two or more elements.

  # bad
  STATES = [:d raft,: Open,: Closed]

  # good
  STATES =%i (draft open closed)

Avoid commas after the last item in Array or Hash, especially if the entries are not in one row.

  # Bad-easier to Move/add/remove items, but still not preferred
  VALUES = [
        1001,
        2020,
        3333,
       ]

  # Bad
  values = [1001, 2020, 3333,]

  # good
  values = [1001, 2020, 3333]

Avoid creating huge gaps in the array.

  arr = []
  arr[100] = 1 # Now, have an array with lots of Nils

When you access the first or last element of an array, you tend to use primary or previous instead of [0] or [-1].

If you want to ensure that the element is unique, use Set instead of Array. Set is better suited to no order, and a unique set of elements that has a quick lookup similar to array-consistent operations and hashes.

Use symbols instead of strings as hashing as possible.

  # bad
  hash = {' One ' => 1, ' two ' => 2, ' Three ' => 3}

  # good
  hash = {one:1, two:2, Three:3}

Avoid using variable objects as hashing.

First use the new hash syntax for 1.9 when your hashing is a symbol.

  # bad
  hash = {: One => 1,: Two => 2,: three => 3}

  # good
  hash = {one:1, two:2, Three:3}

In the same hash literal, do not mix Ruby 1.9 hash syntax with arrows in the form of hash. When you
The resulting keys are not symbols when converted to the syntax of the arrow form.

  # bad
  {a:1, ' B ' => 2}

  # good
  {: A => 1, ' B ' => 2}

With Hash#key? No Hash#has_key? And with Hash#value, no hash#has_value? Matz refers to the too long form in consideration to be discarded.

  # Bad
  hash.has_key? (: Test)
  Hash.has_value? ( Value)

  # good
  hash.key? (: Test)
  Hash.value? ( Value

Use fetch when dealing with hashing that should exist.

  Heroes = {batman: ' Bruce Wayne ', Superman: ' Clark Kent '}
  # bad-if We make a mistake we might don't spot it right awa  Y
  Heroes[:batman] # => "Bruce Wayne"
  Heroes[:supermann] # => Nil

  # Good-fetch raises a keyerror making The problem obvious
  Heroes.fetch (: Supermann)

When you use fetch, use the second parameter to set the default value instead of using custom logic.

  Batman = {name: ' Bruce Wayne ', is_evil:false}

  # bad-if we just use | | operator with falsy value we won ' t get the Expected result
  Batman[:is_evil] | | True # => true

  # Good-fetch work correctly with Falsy values
  Batman . Fetch (: Is_evil, True) # => false

Try to use a fetch plus block instead of setting the default value directly.

  Batman = {name: ' Bruce Wayne '}

  # Bad-if We use the default value, we eager evaluate it
  # so it can slow the PR Ogram down if do multiple times
  batman.fetch (:p owers, get_batman_powers) # get_batman_powers are an expensive call
   # good-blocks are lazy evaluated, so a triggered in case of Keyerror exception Batman.fetch
  (:p owers) {GET_BATM An_powers}

Use Hash#values_at when you need to retrieve a series of values from a hash continuously.

  # bad
  email = data[' email ']
  nickname = data[' nickname ']

  # good
  email, username = data.values_at (' Email ', ' nickname ')

Remember, in Ruby1.9, the performance of the hash is no longer unordered. (Translator Note: Ruby1.9 will remember the sequence of elements inserted)

When traversing a collection, do not modify the collection.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.