SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Wizard lukeurtnowski's Avatar
    Join Date
    Mar 2003
    3 Post(s)
    0 Thread(s)

    symbols confuson

    in this,

    Code Ruby:
    def add(a_number, another_number, options = {})
      sum = a_number + another_number
      sum = sum.abs if options[:absolute]
      sum = sum.round(options[:precision]) if options[:round]
    puts add(1.0134, -5.568)
    puts add(1.0134, -5.568, absolute: true)
    puts add(1.0134, -5.568, absolute: true, round: true, precision: 2)
    Why is a symbol sometimes have a : before or after the name?
    Last edited by Pullo; Jul 22, 2013 at 23:40. Reason: Added code tags
    "Oh, and Jenkins--apparently your mother died this morning."

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    219 Post(s)
    12 Thread(s)
    A symbol always has a : in front of its name, usually followed by a non-quoted string, e.g. :pullo
    They are also immutable. Their value remains constant during the entirety of the program and they never appear on the left side of an assignment.

    In the above example, I think you're probably getting confused with the arguments you are passing to the add method.

    As of Ruby 1.9 hashes can be declared using a new syntax.

    Ruby 1.8 syntax:
    Code Ruby:
    {:key1 => "value1", :key2 => "value2"}

    Ruby 1.9 syntax:
    Code Ruby:
    {key1: "value1", key2: "value2"}

    So this:

    Code Ruby:
    puts add(1.0134, -5.568, absolute: true)

    Could also be written like this:

    Code Ruby:
    puts add(1.0134, -5.568, :absolute => true)

    and this:

    Code Ruby:
    puts add(1.0134, -5.568, absolute: true, round: true, precision: 2)

    could also be written like:

    Code Ruby:
    puts add(1.0134, -5.568, :absolute => true, :round => true, :precision => 2)

    In short: symbols always have a : in front of them. You are getting confused with the new Hash syntax introduced in Ruby 1.9

    Further reading:


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts