ForNext
Only Do What Only You Can Do
137. default value, computed value
Hyperpolyglot Interpreted Languages: PHP, Perl, Python, Ruby より (2012.05.08)
VBScript
JScript
Perl
my %counts; $counts{'foo'} += 1 define a tied hash for computed values and defaults other than zero or empty string
PHP
$counts = array(); $counts['foo'] += 1; extend ArrayObject for computed values and defaults other than zero or empty string.
Python
from collections import defaultdict counts = defaultdict(lambda: 0) counts['foo'] += 1 class Factorial(dict): def __missing__(self, k): if k > 1: return k * self[k-1] else: return 1 factorial = Factorial()
Ruby
counts = Hash.new(0) counts['foo'] += 1 factorial = Hash.new do |h,k| k > 1 ? k * h[k-1] : 1 end