[Ruby笔记]24.Ruby全局变量 $global_variable

$global_variable

  • $符号是全局变量的标识;
  • time << "#{$minute} : " if $minute ,如果minute 非空就加入到time 之中;
  • 可以看到,给$变量赋值的时候都是不带t.xxx 开头的,直接就$gvar赋值了,结果是全局变量真的就可以在整个irb里管用的;
  • irb打开着,没关;
PS C:\Users\Administrator> irb --simple-prompt
>> class Time
>>  def hour_minute_seconds
>>   time = $hour + ":"
>>   time << "#{$minute} : " if $minute
>>   time << "#{$second}"
>>  end
>> end
=> :hour_minute_seconds

>> t = Time.new
=> 2016-06-14 01:21:15 +0800

>> $hour = "13"
=> "13"
>> $minute = "47"
=> "47"
>> $second = "59"
=> "59"

>> t.hour_minute_seconds
=> "13 : 47 : 59 "

reference

《The Well-Grounded Rubyist, Second Edition》
(https://www.manning.com/books/the-well-grounded-rubyist-second-edition)
5.2.1. Global scope and global variables

ギャー逃げろ~
ヾ(>Д< )ノ
  (  (
   @@≡
http://emoji.vis.ne.jp/nigero6.htm

你可能感兴趣的:(Ruby(初学))