रूबी भाषा में एक-कथन में कई स्थितियों का उपयोग करना
Nov 24 2020
मैं रूबी में कुछ इस तरह लिखता हूं:
if a.max == a[0]
brand = b[0]
elsif a.max == a[1]
brand = b[1]
elsif a.max == a[2]
brand = b[2]
elsif a.max == a[3]
brand = b[3]
end
a
और b
दोनों अद्वितीय सरणियाँ हैं।
सभी जांच करने के लिए कोई तरीका है if
और elsif
एक ही हालत में है?
के लिए केवल एक ही शर्त a[0]
, a[1]
, a[2]
और a[3]
?
जवाब
6 spickermann Nov 24 2020 at 17:03
एरे # इंडेक्स इन जैसे मामलों में मदद कर सकता है (आकार का मान a
और b
समान है):
brand = b[a.index(a.max)]
ऐसे मामले जिनमें सरणी a
खाली हो सकती है, आपको एक त्रुटि से बचने के लिए एक अतिरिक्त स्थिति की आवश्यकता होगी:
index = a.index(a.max)
brand = b[index] if index
4 CarySwoveland Nov 24 2020 at 17:33
दो और तरीके:
a = [3, 1, 6, 4]
b = [2, 8, 5, 7]
b[a.each_index.max_by { |i| a[i] }]
#=> 5
या
b[a.each_with_index.max_by(&:first).last]
#=> 5
4 Stefan Nov 24 2020 at 17:55
मान लिया a
और b
एक ही आकार है, जैसे
a = [2, 5, 8, 1]
b = [:a, :b, :c, :d]
आप गठबंधन कर सकते हैं zipऔर max:
a.zip(b).max.last # or more explicit: a.zip(b).max_by(&:first).last
#=> :c # or reversed: b.zip(a).max_by(&:last).first
या max_byऔर with_index:
b.max_by.with_index { |_, i| a[i] }
#=> :c
2 TimurShtatland Nov 24 2020 at 17:30
यदि आपकी सरणी में कई मैक्सिमा हैं, तो आप उस सरणी के सूचकांकों को प्राप्त करना चाहते हैं जो सभी मैक्सिमा के अनुरूप हो:
a = [10, 12, 12]
b = [:a, :b, :c]
# Compute and store the maximum once, to avoid re-computing it in the
# loops below:
a_max = a.max
idxs = a.each_with_index.select{ |el, idx| el == a_max }.map{ |el, idx| idx }
# or:
idxs = a.each_with_index.map{ |el, idx| idx if el == a_max }.compact
puts "#{idxs}"
# [1, 2]
puts "#{idxs.map{ |idx| b[idx] }}"
# [:b, :c]