ruby 将字符串转为数组_Ruby程序将数组打印为字符串
ruby 將字符串轉為數組
將數組打印為字符串 (Printing an array as string)
Given an array and we have to print it as a string in Ruby.
給定一個數組,我們必須在Ruby中將其打印為字符串。
Ruby provides you various alternatives for the single problem. There are plenty of predefined methods which helps you in making your code less complex. The?method join is one of them. When we have to print the array elements like a string, join proves its functionality. Another way is also available which facilitates loop and concatenation operator. Let us see both of them in the following code.
Ruby為您提供了多種解決單個問題的方法。 有很多預定義的方法可以幫助您簡化代碼。 方法聯接是其中之一。 當我們必須像字符串一樣打印數組元素時,join證明了它的功能。 也可以使用另一種方式來簡化循環和串聯運算符。 讓我們在下面的代碼中看到它們兩者。
join() method
join()方法
join method is used to join the elements of an array. It can be invoked with parameters after which the parameter passed will be reflected between each join.
join方法用于連接數組的元素。 可以使用參數調用它,然后在每個聯接之間反映傳遞的參數。
Ruby代碼將數組打印為字符串 (Ruby code to print an array as string)
=begin Ruby program to print an array as string. =end# array arr= Array["Haridwar","Dehradun","Graphic_Era","Includehelp"]# converting to string joinarr1=arr.join(" ") #using join method # printing puts joinarr1#using for loop and .to_s method joinarr2="" for i in 0..arr.lengthjoinarr2=joinarr2+arr[i].to_s+ " " endputs joinarr2Output
輸出量
Haridwar Dehradun Graphic_Era Includehelp Haridwar Dehradun Graphic_Era IncludehelpCode explanation:
代碼說明:
In the above code, one can observe that we have invoked join method with no parameters passed because we wanted to keep the join blank. When you scan down, you will observe that for loop is used which is providing the expressions that are concatenating each array element using + operator.
在上面的代碼中,可以看到我們調用了join方法而沒有傳遞任何參數,因為我們希望保持空白。 向下掃描時,您會發現使用了for循環,該循環提供了使用+運算符將每個數組元素連接在一起的表達式。
翻譯自: https://www.includehelp.com/ruby/print-an-array-as-string.aspx
ruby 將字符串轉為數組
總結
以上是生活随笔為你收集整理的ruby 将字符串转为数组_Ruby程序将数组打印为字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java代码中何处以main开始_自测题
- 下一篇: ruby 覆盖率测试_Ruby方法覆盖