Menu
CoddyTech

Symbols and Keys

Lesson 7 of 48 in Coddy's Ruby for PHP Developers course.

PHP arrays accept integer and string keys and coerce some key forms; there is no Ruby-style symbol literal. Ruby symbols differ from same-spelled strings and are common for named options. A PHP string key repeated twice updates one entry, whereas a Ruby symbol and string can occupy two separate entries. Be deliberate about key representation at boundaries.

PHP: complete program

<?php
$data = ["mode" => 1];
$data["mode"] = 2;
echo count($data), "\n", $data["mode"], "\n";

Ruby: complete program

data = {mode: 1, "mode" => 2}
puts data.length
puts data[:mode]
challenge icon

Challenge

Easy

Read one command: start, stop or any other text. Look up its symbol in a fixed table: start maps to 1, stop maps to 0. Unknown commands return -1.

Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.

Your code goes in exercise.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

require_relative 'exercise'
def check(value)
  raise 'Public API check failed' unless value
end

puts solve(STDIN.read)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Ruby for PHP Developers

Practice on your own: Online Ruby compiler