ruby 集合 分组_在Ruby中打印集合的元素
ruby 集合 分組
We have gone through the implementation of sets in Ruby. They are very similar to arrays. Now, let us see how we print the elements present in a set. There are no indexes present in the sets because sets are used to store the large elements.
我們已經完成了Ruby中集合的實現。 它們與數組非常相似。 現在,讓我們看看如何打印一組中存在的元素。 集合中沒有索引,因為集合用于存儲大元素。
Methods used:
使用的方法:
set.add(): This method is used to add the elements in the set. It would only add the elements which are not present in the set. You will not get an error if you try to add duplicate elements but duplicate elements will not be reflected in the set.
set.add() :此方法用于添加集合中的元素。 它只會添加集合中不存在的元素。 如果您嘗試添加重復的元素,但不會出現錯誤,但是重復的元素將不會反映在集合中。
set.each: This method is used to print the elements in the set. Whereas you cannot make changes in the set or in other words you cannot manipulate the set elements with the help of this method. We have got several set methods to manipulate the elements. This method will only print the elements in the forward direction.
set.each :此方法用于打印集合中的元素。 然而,您無法在集合中進行更改,或者換句話說,您無法借助此方法來操作集合元素。 我們有幾種設置方法來操作元素。 此方法將僅向前打印元素。
set.size(): This method tells the size of the set or the number of elements present in the set.
set.size() :此方法告知集合的大小或集合中存在的元素數。
Variables used:
使用的變量:
vegetable: This is a set that contains the names of vegetables.
蔬菜 :這是一個包含蔬菜名稱的集合。
i: This is working as a tracking variable which is telling the order of elements present in the set.
i :這是一個跟蹤變量,用于指示集合中元素的順序。
Code:
碼:
=begin Ruby program to implement set.each method =endrequire 'set'# Creation of new Set. Vegetable = Set.new(["potato", "tomato","brinjal","onion"])Vegetable.add("potato")Vegetable.add("tomato")Vegetable.add("Beetroot")puts "Number of elements in set are #{Vegetable.size()}"i = 1 Vegetable.each do |n|puts "#{i} element is #{n}"i = i + 1 endOutput
輸出量
Number of elements in set are 5 1 element is potato 2 element is tomato 3 element is brinjal 4 element is onion 5 element is BeetrootExplanation:
說明:
In the above code, first, we have created a set named Vegetable. We have made use of set.add() method to add more elements in the Vegetable set. Our objective is to print the elements present in the set. We can only do this with the help of the set.each method. It can also be considered as a loop that works on specific variables in Ruby. The variable ‘n’ is receiving the elements present in the set one by one. We have employed a variable i to print the order of the elements.
在上面的代碼中,首先,我們創建了一個名為Vegetable的集合。 我們利用set.add()方法在Vegetable集中添加了更多元素。 我們的目標是打印集中存在的元素 。 我們只能在set.each方法的幫助下執行此操作 。 也可以將其視為對Ruby中特定變量起作用的循環。 變量“ n”正在一個接一個地接收集合中存在的元素。 我們使用了變量i來打印元素的順序。
翻譯自: https://www.includehelp.com/ruby/print-the-elements-of-a-set.aspx
ruby 集合 分組
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的ruby 集合 分组_在Ruby中打印集合的元素的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何使用React Native样式表?
- 下一篇: ruby hash方法_Ruby中带有示