-1

The following code is generating an error and I cannot see the issue. Can anyone help?

customer_array = [‘Ken’,’William’,’Catherine’,’Mark’,’Steve’,’Sam’]
customer_hash = {
‘Ken’ => ‘Fiction’,
‘William’ => ‘Mystery’,
‘Catherine’ => ‘Computer’,
‘Mark’ => ‘Fiction’,
‘Steve’ => ‘Sports’,
‘Sam’ => ‘Fiction’
}
# => customer_array.rb:6: syntax error, unexpected tSTRING_BEG , expecting '}'
# 'William' => 'Mystery'
#      ^
sawa
  • 165,429
  • 45
  • 277
  • 381
Ninja2k
  • 819
  • 3
  • 9
  • 34

3 Answers3

6

The problem seems to be with those weird back quotes. Try this instead:

customer_array = ["Ken","William","Catherine","Mark","Steve","Sam"]
customer_hash = {
    "Ken" => "Fiction",
    "William" => "Mystery",
    "Catherine" => "Computer",
    "Mark" => "Fiction",
    "Steve" => "Sports",
    "Sam" => "Fiction"
}
beatgammit
  • 19,817
  • 19
  • 86
  • 129
  • You can also use single quotes, as @slivu said in his answer. Single quote or double quote works, but backquote doesn't. – beatgammit Nov 16 '12 at 23:32
1

your quotes are non-ASCII chars.

replace them with ASCII ' or ".

or add # encoding: UTF-8 to the beginning of your file and wrap them into ASCII quotes, like this:

# encoding: UTF-8

customer_hash = {
  "‘Ken’" => "‘Fiction’",
}
-1

You have lots of keys => values a hash contains one key (before the arrow) and one value (after the arrow)

You can make an array of hashes. Ruby on rails uses this.

You have to fix the quotes

customer_hash = {
    "Ken" => "Fiction",
    "William" => "Mystery",
    "Catherine" => "Computer",
    "Mark" => "Fiction",
    "Steve" => "Sports",
    "Sam" => "Fiction"
}

But why not do it like this

customer_array_of_hashes =  [
{'Ken' => 'Fiction'},
{'William' => 'Mystery'},
{'Catherine' => 'Computer'},
{'Mark' => 'Fiction'},
{'Steve'=> 'Sports'},
{'Sam' => 'Fiction'}
]

Then You can loop trough it like this

customer_array_of_hashes.each do|hash|
 hash.each do |key, value|
  puts "lastname: " + value + ", firstname: " + key
 end
end

You can find alot of all methods on all ruby Classes here

Ruby API

And rails extra methods here

Ruby on rails API

One tip in the end

Try this

irb(main):039:0> customer_array_of_hashes.class
=> Array

If you ever wounder what class you have in ruby the class method will give the answer.

Ok you know that customer_array_of_hashes is an array. One method you can use on arrays is .first

Try this

irb(main):040:0> customer_array_of_hashes.first.class
=> Hash

Ok it is an array of hashes!

Good look!

Andreas Lyngstad
  • 4,887
  • 2
  • 36
  • 69