पर्ल मूलभूत मूल्यों के बारे में बहुत अच्छा है:क्या मैं रूबी में डिफ़ॉल्ट मानों के साथ एक सरणी बना सकता हूं?
: [email protected]; perl -e '@foo; printf "%d\n", $foo[123]'
0
: [email protected]; perl -e '%foo; printf "%d\n", $foo{bar}'
0
रूबी कम से कम हैश के लिए, एक ही कर सकते हैं:
>> foo = Hash.new(0)
=> {}
>> foo[:bar]
=> 0
लेकिन मालूम होता है एक ही सरणियों के लिए काम नहीं करता:
>> foo = Array.new(0)
=> []
>> foo[123]
=> nil
>> foo[124] = 0
=> 0
>> foo[456] = 0
=> 0
>> foo[455,456]
=> [nil, 0]
क्या यह सरणी के लिए डिफ़ॉल्ट मान प्रदान करना संभव है, इसलिए जब वे स्वतः विस्तारित होते हैं, तो वे शून्य के बजाय 0 से भरे होते हैं?
बेशकमैं इस पर काम कर सकते हैं, लेकिन लागत से अभिव्यक्ति के लिए:
>> foo[457,458] = 890, 321
=> [890, 321]
>> foo[456] += 789
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.+
>> foo.inject(0) {|sum, i| sum += (i || 0) }
=> 1211
>> foo.inject(:+)
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.+
अद्यतन 1: मेरे साथियों में से एक ने कहा कि मैं #inject
इस मुद्दे को हल करने के लिए #compact
उपयोग कर सकते हैं, और #to_i
>> foo.include? nil
=> true
>> foo.compact.inject(:+)
=> 1211
>> foo[456,457]
=> [0, 890, 321]
>> foo[455..457]
=> [nil, 0, 890]
>> foo[455..457].map(&:to_i)
=> [0, 0, 890]
अद्यतन 2: के लिए Andrew Grimm के लिए धन्यवाद मानक तत्व-एट-सूचकांक इस मुद्दे को हल करने के लिए +=
मुद्दे का समाधान:
>> foo = []
=> []
>> def foo.[](i)
>> fetch(i) {0}
>> end
=> nil
>> foo[4]
=> 0
>> foo
=> []
>> foo[4] += 123
=> 123
>> foo
=> [nil, nil, nil, nil, 123]
अद्यतन 3: इस अजीब एक तिल की तरह लग रहे करने के लिए शुरू कर रहा है!
>> foo
=> [nil, nil, nil, nil, 123]
>> foo[-2..-1]
TypeError: can't convert Range into Integer
लेकिन हम साथ सौदा कर सकते हैं:
>> def foo.[](index)
>> if index.is_a? Range
>> index.map {|i| self[i] }
>> else
?> fetch(index) { 0 } # default to 0 if no element at index; will not cause auto-extension of array
>> end
>> end
=> nil
>> foo
=> [nil, nil, nil, nil, 123]
>> foo[-2..-1]
=> [nil, 123]
मैं अब (स्वीकार) स्वीकार करना होगा कि मैं Array
उपवर्ग मेरे कोड को अव्यवस्थित से बचने के लिए होगी:
class MyClass
class ArrayWithDefault < Array
def [](index)
if index.is_a? Range
index.map {|i| self[i] }
else
fetch(index) { 0 } # default to 0 if no element at index; will not cause auto-extension of array
end
end
end
end
के लिए धन्यवाद सभी रचनात्मक समाधान। वास्तव में TIMTOWTDI!
यदि आपको स्पैस सरणी की आवश्यकता है, तो पूर्णांक कुंजी के साथ हैश का उपयोग करने में क्या गलत है? – Simon
मुझे आश्चर्य है कि क्या किसी भी PHP डेवलपर्स ने शिकायत की है कि रूबी में उनकी सरणी/हैश डेटा संरचना मौजूद नहीं है। –
साइमन: मैं पहले स्थान पर हैश के साथ गया था, लेकिन कुछ # मैप्स और # इंजेक्ट्स के साथ मुझे दर्द है जो मुझे करने की ज़रूरत है। –