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.length
	joinarr2=joinarr2+arr[i].to_s+ " "
end

puts joinarr2

Output

输出量

Haridwar Dehradun Graphic_Era Includehelp
Haridwar Dehradun Graphic_Era Includehelp

Code 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 将字符串转为数组

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值