我是Perl的新手,在阅读了一些代码之后,我偶然发现了这句话:
my_hash{string}++
其中my_hash
变量是哈希,字符串是任意字符串。
我的猜测是:
my_hash{string} = string++
并且任何人都可以将这行代码翻译成Ruby吗?
答案 0 :(得分:5)
$var++;
装置
$var = $var + 1;
但它实际上更接近
$var = defined($var) ? $var+1 : 1;
因为LHS被定义为零(没有警告),如果它未定义。类似地,
$my_hash{key}++;
相当于
$my_hash{key} = defined($my_hash{key}) ? $my_hash{key}+1 : 1;
(在罕见的角落案件中还有一些其他细微差别,但你不关心。)
Ruby等价物是
my_hash["key"] = my_hash["key"].to_i + 1;
或
# If my_hash["key"] is a number,
# Or if "my_hash" was created using "my_hash = Hash.new(0)".
my_hash["key"] += 1;
$ perl -E'
my %my_hash;
$my_hash{key}++; say $my_hash{key};
$my_hash{key}++; say $my_hash{key};
'
1
2
$ ruby -e'
my_hash = {};
my_hash["key"] = my_hash["key"].to_i + 1; p my_hash["key"];
my_hash["key"] = my_hash["key"].to_i + 1; p my_hash["key"];
'
1
2
$ ruby -e'
my_hash = {};
my_hash["key"] = 0;
my_hash["key"] += 1; p my_hash["key"];
my_hash["key"] += 1; p my_hash["key"];
'
1
2
$ ruby -e'
my_hash = Hash.new(0);
my_hash["key"] += 1; p my_hash["key"];
my_hash["key"] += 1; p my_hash["key"];
'
1
2
答案 1 :(得分:1)
my_hash{string}++
正在递增存储在散列中的整数,例如:
my %my_hash;
$my_hash{hi} = 0;
$my_hash{hi}++;
print "$_ $my_hash{$_}\n" for (keys %my_hash);
#> hi 1
使用[]
访问Ruby哈希,Ruby不实现++
,因此您必须使用+= 1
。那么等效的Ruby代码就是:
my_hash = {}
my_hash['hi'] = 0
my_hash['hi'] += 1
puts my_hash
#> {"hi"=>1}