Hash name is not recognized by Ruby unless first letter is capitalized

Hi, all:

My little test code below will not recognize the hash variable
if its first letter is not capitalized. If the first letter is
capitalized,
then everything is OK. I’ll appreciate any explanation for this
behavior.

===========================

failure if declared as “mc”. Must capitalize “M”, lowercase “m”

such as “mc” will result in compilation errors.

Mc = { “a” => “aay”, “b” => “bee”, “c” => “cee” }

def pronounce (aStr)
array_of_chars = aStr.split("");
array_of_chars.map { |eachChar| Mc[eachChar] };
end

puts “#{pronounce(“abc”)}”;

Thanks,

PL

key “def” define a scope .

function pronounce not see outside variable “mc”,
“Mc” is constance, can used by anywhere.

2013/5/10 Phil L. [email protected]

Am Fri, 10 May 2013 15:10:08 +0900
schrieb Phil L. [email protected]:

Hi, all:

My little test code below will not recognize the hash variable
if its first letter is not capitalized. If the first letter is
capitalized,
then everything is OK. I’ll appreciate any explanation for this
behavior.

In Ruby, everything starting with a capital letter is a constant.
Constants are visible globally anywhere in a program, hence you can
access it in your method.

The “def” keyword creates a new scope where you can’t access veriables
from the outside, which is why you can’t see them inside the method.

Vale,
Marvin


Blog: http://pegasus-alpha.eu/blog

ASCII-Ribbon-Kampagne () | ASCII Ribbon Campaign ()

Try reading this page, it should help you understand a bit of how Ruby’s
variables work.
http://www.techotopia.com/index.php/Ruby_Variable_Scope