本文共 2877 字,大约阅读时间需要 9 分钟。
ruby字符串截取字符串
Here, we are implementing a Ruby program to reverse a string.
在这里,我们正在实现一个Ruby程序来反转字符串。
Methods used:
使用的方法:
gets: This method is a public instance method of String class which is used to take input from the console.
gets :此方法是String类的公共实例方法,用于从控制台获取输入。
puts: This method is a public instance method of String class which is used to print Strings on the console.
puts :此方法是String类的公共实例方法,用于在控制台上打印String。
reverse: This method is a public instance method of String class which is used to reverse the String object.
reverse :此方法是String类的公共实例方法,用于反转String对象。
split: This method is a public instance method of String class which is used to convert the String into array instance.
split :此方法是String类的公共实例方法,用于将String转换为数组实例。
length: This method is a public instance method of String class which is used to find the number of characters present in the String.
length :此方法是String类的公共实例方法,用于查找String中存在的字符数。
times: This is a kind of loop through which the statement iterates for a given number of times.
times :这是一种循环,语句可循环执行给定次数。
push: This method is used to add character to the array object.
push :此方法用于向数组对象添加字符。
pop: This method is used to remove the character from the array object.
pop :此方法用于从数组对象中删除字符。
join: This method is used to covert the Array object into the String.
join :此方法用于将Array对象隐藏到String中。
Example 1: Without using library method reverse
示例1 :不使用库方法反向
=begin Ruby program to reverse a String. =enddef rev_str(str) s_str = str.split("") new_str = [] str.length.times{ new_str.push(s_str.pop)} new_str.joinendputs "Enter the String you want to reverse:"string = gets.chompputs "The reversed String is #{rev_str(string)}"
Output
输出量
Enter the String you want to reverse: includehelp.comThe reversed String is moc.plehedulcni
Explanation:
说明:
In the above code, you can observe that we have defined a function that is responsible for reversing the String object. First, we have converted the String into an Array object then after processing it, we have converted it back to a String object.
在上面的代码中,您可以观察到我们已经定义了一个函数,该函数负责反转String对象。 首先,我们将String转换为Array对象,然后在对其进行处理后,将其转换回String对象。
Example 2:
范例2:
=begin Ruby program to reverse a String. =endputs "Enter the String you want to reverse:"string = gets.chomprev_string = string.reverseputs "The reversed String is #{rev_string}"
Output
输出量
RUN 1:Enter the String you want to reverse: includehelp.comThe reversed String is moc.plehedulcniRUN 2:Enter the String you want to reverse: Hello World!The reversed String is !dlroW olleH
Explanation:
说明:
In the above code, you can observe that we have invoked the method which is a public instance method defined in Ruby's library for reversing the String. For creating the permanent changes in the String you can invoke .
在上面的代码中,您可以观察到我们调用了方法,这是在Ruby的库中定义的用于反转String的公共实例方法。 为了在字符串中创建永久更改,您可以调用 。
翻译自:
ruby字符串截取字符串
转载地址:http://uwozd.baihongyu.com/