Language: Ruby Question: Is there a way to automatically view the \"array\" vari
ID: 3756508 • Letter: L
Question
Language: Ruby
Question: Is there a way to automatically view the "array" variable alphabetically. Meaning, I don't want to call the ".sort" method after the class is closed. So when I say: "o.array" I want the class to display whatever is inside "o" alphabetically.
Thanks ^_^
Class Some0bject attr_accessor :array 18 def initialize self.array[l end end o = Someobject.new o.array.push :a o.array.push :b o.array [a, b, :c] share edit edited Sep 12'10 at 1:15 answered Sep 12 '10 at 0:59 Ryan McGeary 84k 10 8496Explanation / Answer
Yes, there a way to automatically view the "array" variable alphabetically.
Class needs a method to display values alphabetically.
So we can use methods display1, display2 to print array in Asc or Desc order.
#!/usr/bin/ruby
class Marks
attr_accessor :english
def initialize
self.english = []
end
def display1()
puts ''
puts 'display1 >> your array Asc'
p english.sort
puts ''
end
def display2()
puts ''
puts 'display2 >> your array Desc'
p english.reverse
puts ''
end
end
o = Marks.new
p o.english
o.english = [5,3,99,1]
o.english.push(22)
p o.english
o.display1()
o.display2()
p o.english
# Output:-
# []
# [5, 3, 99, 1, 22]
# display1 >> your array Asc
# [1, 3, 5, 22, 99]
# display2 >> your array Desc
# [22, 1, 99, 3, 5]
# [5, 3, 99, 1, 22]
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.