Search code examples
ruby-on-railsrubyservertcpsymbols

How to represent a value with symbol in ruby?


I am here try to make a simple server with ruby.

I was thinking of using symbols to make the code a bit efficient.But I am facing a problem which I don't understand. I tried online resources and other stuff I could get my hands on but it doesn't seems to help my problem.

As you can see in line 8 I represent the variable path with an symbol of the same name. But when I am displaying it on line 12 it's showing the word path instead of the value the symbol it's representing.

I have an another doubt. As I know we can represent symbols in two ways one where the colon is in front of the name( like :symbol) and at the end of the name(like symbol:). But When I try to put the output using the second representation(like symbol:) it leads to an error as server_beta.rb:14: syntax error, unexpected keyword_end server_beta.rb:24: syntax error, unexpected end-of-input, expecting keyword_end.

If anyone could explain this it would be much of a great help. Thanks in advance for your help

  5 def parse(request)
  6   method, path, version = request.lines[0].split
  7     {
  8     path: path,
  9     method: method
 10   }
 11 
 12     puts :path #Variation 1
 13     puts path: #Variation 2
 14 end

Output : path (Variation 1)


Solution

  • I think you are confused about the use of symbols by some of the conventions in Ruby and Rails.

    Symbols are not variables. Variables are used to store values. Symbols are lighter weight versions of strings. They can be used in place of strings in places like hash keys.

    hash1 = {'name' => 'Mary', 'age' => 30}
    puts hash1['name']
    #=> 'Mary'
    
    hash2 = {:name => 'John', :age => 32}
    puts hash2[:age]
    #=> '32'
    

    Ruby introduced a new hash notation to make things cleaner when using symbols for hash notation that eliminated the "hash rocket" =>

    hash2 = {name: 'John', age: 32}
    

    To take advantage of the conventions in Rails they came up with "hash with indifferent access". So it is a hash that allows you to use either a string or its symbol version interchangeably in a hash:

    hash2 = = ActiveSupport::HashWithIndifferentAccess.new
    hash2['name'] = 'John'
    puts hash2[:name]
    #=> 'John'
    puts hash2['name']
    #=> 'John'
    

    In Rails you assign values to columns in a table using symbols:

    p = Person.new(name: 'John', age: '32')
    

    you then access them through method names that are string versions of the column name:

    puts p.name #=> 'John'

    I think you are missing some real foundations of Ruby. I would study that more and then maybe do one of the tutorials that involves rebuilding Rails so you see how the syntax of Ruby relates to the conventions in Rails.