Week 2, day 6
All I want is to print out my menu. To be precise, my hash keys and values. Surely it can't be that hard, right? Wrong!
Here is where I start to hate myself for forgetting things I've already learnt the hard way. Luckily though, in my past life I was a bit of a pro at trouble-shooting the technical side of creative projects, so this feeling is very familiar to me.
I find I have to make the same mistake 2 or 3 times before the lesson really sinks in, and I can say for sure I won't be repeating this mistake.
Here's my menu and how I want it to appear:
1 menu = { meal_small: 5, meal_medium: 10, meal_large: 15 }
meal_small: £5
meal_medium: £10
meal_large: £15
This is such a silly mistake that I'm embarassed to even confess to it, but I think it's important that I do.
1 to_return = ''
2 menu.each { |key, value| to_return << key.to_s << ': £' << value.to_s << '\n' }
3 puts to_return
"mealsmall: £5\nmealmedium: £10\nmeal_large: £15\n"
So, that's obviously not what I wanted, and I did actually struggle for a little while wrapping my head around the problem, IRB to the rescue.
Then I remembered that you can't use escape characters in single-quotes, once I amended all singles to double quotes it actually worked.
1 to_return = ""
2 menu.each { |k, v| to_return << k.to_s << ": £" << v.to_s << "\n" }
3 puts to_return
4
5 to_return = ""
6 menu.map { |k, v| to_return << "#{k.to_s}: £#{v.to_s}\n" }
7 puts to_return
Both of the above give the desired output:
meal_small: £5
meal_medium: £10
meal_large: £15
Here are the tests I ran:
1 menu = { meal_small: 5, meal_medium: 10, meal_large: 15 }
2
3 to_return = ''
4 menu.map { |key, value| to_return << key.to_s + ': £' + value.to_s }
5 p '1'
6 puts to_return
7
8 to_return = ''
9 menu.map { |key, value| to_return << "#{key}: £#{value}" }.join(', ')
10 p '2'
11 puts to_return
12
13 to_return = ''
14 menu.each { |key, value| to_return << key.to_s << ': £' << value.to_s << '\n' }
15 p '3'
16 puts to_return
17
18 # to_return = ''
19 # menu.join(': £', ', ')
20 # p '4'
21 # puts to_return
22
23 to_return = ""
24 menu.each { |k, v| to_return << k.to_s << ": £" << v.to_s << "\n" }
25 p "5"
26 puts to_return
27
28 to_return = ""
29 menu.map { |k, v| to_return << "#{k.to_s}: £#{v.to_s}\n" }
30 p "6"
31 puts to_return
32
33 to_return = ''
34 menu.each { |k, v| to_return << k.to_s << ': £' << v.to_s << '\n' }
35 p '7'
36 puts to_return
37
38 to_return = ''
39 menu.map { |k, v| to_return << '#{k.to_s}: £#{v.to_s}\n' }
40 p '8'
41 puts to_return
And the STDOUT:
1 "1"
2 meal_small: £5meal_medium: £10meal_large: £15
3
4 "2"
5 meal_small: £5meal_medium: £10meal_large: £1
6
7 "3"
8 meal_small: £5\nmeal_medium: £10\nmeal_large: £15\n
9
10 "5"
11 meal_small: £5
12 meal_medium: £10
13 meal_large: £15
14
15 "6"
16 meal_small: £5
17 meal_medium: £10
18 meal_large: £15
19
20 "7"
21 meal_small: £5\nmeal_medium: £10\nmeal_large: £15\n
22
23 "8"
24 #{k.to_s}: £#{v.to_s}\n#{k.to_s}: £#{v.to_s}\n#{k.to_s}: £#{v.to_s}\n