`
isiqi
  • 浏览: 16483091 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

Ruby String Replacement, Substitution and Insertion

阅读更多

Changing a Section of a String

Ruby allows part of a string to be modified through the use of the []= method. To use this method, simply pass through the string of characters to be replaced to the method and assign the new string. As is often the case, this is best explained through the use of an example:

myString = "Welcome to JavaScript!"



myString["JavaScript"]= "Ruby"



puts myString

=> "Welcome to Ruby!"

As you can see, we replaced the word "JavaScript" with "Ruby".

The []= method can also be passed an index representing the index at with the replacement is to take place. In this instance the single character at the specified location is replaced by the designated string:

myString = "Welcome to JavaScript!"

myString[10]= "Ruby"



puts myString

=> "Welcome toRubyJavaScript!"

Perhaps a more useful trick is to specify an index range to be replaced. For example we can replace the characters from index 8 through to index 20 inclusive:

myString = "Welcome to JavaScript!"

=> "Welcome to JavaScript!"



myString[8..20]= "Ruby"

=> "Ruby"



puts myString

=> "Welcome Ruby!"

Ruby String Substitution

The gsub and gsub! methods provide another quick and easy way of replacing a substring with another string. These methods take two arguments, the search string and the replacement string. The gsub method returns a modified string, leaving the original string unchanged, whereas the gsub! method directly modify the string object on which the method was called:

myString = "Welcome to PHP Essentials!"

=> "Welcome to PHP Essentials!"



myString.gsub("PHP", "Ruby")

=> "Welcome to Ruby Essentials!"

An entire string, as opposed to a substring, may be replaced using the replace method:

myString = "Welcome to PHP!"

=> "Welcome to PHP!"



myString.replace "Goodbye to PHP!"

=> "Goodbye to PHP!"

Repeating Ruby Strings

A string may be multiplied using the * method (not something I have ever needed to do myself, but the capability is there if you need it):

myString = "Is that an echo? "

=> "Is that an echo? "



myString * 3

=> "Is that an echo? Is that an echo? Is that an echo? "

Inserting Text into a Ruby String
@import "/extensions/GoogleAdSense/GoogleAdSense.css";

So far in this chapter we have looked exclusively at changing the existing text contained in a Ruby string object. Another common requirement is to insert new text at a certain location in a string. This is achieved in Ruby using the insert method. The insert method takes as arguments index position into the string where the insertion is take place, followed by the string to be inserted


myString = "Paris in Spring"



myString.insert 8, " the"

=> "Paris in the Spring"

Ruby chomp and chop Methods

The purpose of the chop method is to remove the trailing character from a string:

myString = "Paris in the Spring!"

=> "Paris in the Spring!"



myString.chop

=> "Paris in the Spring"

Note that chop returns a modified string, leaving the original string object unchanged. Use chop! to have the change applied to the string object on which the method was called.

The chomp method removes record separators from a string. The record separator is defined by the $/ variable and is, by default, the new line character (\n). As with the chop method the chomp! variant of the method applies the change to string object on which the method is called:

myString = "Please keep\n off the\n grass"

=> "Please keep\n off the\n grass\n"



myString.chomp!

=> "Please keep\n off the\n grass"

Reversing the Characters in a String

The reverse method is used to reverse the contents of a string:

myString = "Paris in the Spring"

=> "Paris in the Spring"



myString.reverse

=> "gnirpS eht ni siraP"

Once again, not something I've ever needed to do in all my years as a developer, but you never know when you might need to do it.

分享到:
评论

相关推荐

    String-Substitution:简单的运行时字符串替换函数

    my $subbed = gsub($string, $pattern, $replacement); 描述 该模块是一组函数,用于使用在运行时创建的替换字符串或函数对字符串启用(全局)替换。 它旨在在运行时从输入中获取字符串、模式和替换字符串,并在不...

    String-replacement-operation.rar_operation

    为了深入理解这个问题,我们可以参考提供的`String-replacement-operation.txt`文件,其中可能包含了具体的代码示例、算法描述或者测试用例。通过分析这个文件,我们可以更清楚地了解如何在堆结构上进行字符串的置换...

    StringAPI.java

    String replace(CharSequence target, CharSequence replacement) String[] split(String regex) boolean contains(CharSequence s):当且仅当此字符串包含指定的 char 值序列时,返回 true int indexOf(String...

    java中的String类常用方法解析(一)

    - `replaceAll(String regex, String replacement)`:使用正则表达式替换匹配的部分。 7. **分割字符串** - `split(String regex)`:根据正则表达式将字符串分割成数组。 8. **获取字符/字节数组** - `...

    JAVA【第5章:面向对象基础】_String类的常用方法.rar

    - `replaceAll(String regex, String replacement)`:使用正则表达式替换匹配项。 - `replaceFirst(String regex, String replacement)`:只替换第一个匹配项。 9. **比较字符串顺序**: - `compareTo(String ...

    关于String类的一些方法

    - `replaceAll(String regex, String replacement)`:使用正则表达式进行替换。 6. **分割字符串**: - `split(String regex)`:根据正则表达式将字符串分割成数组。 7. **提取子串**: - `substring(int ...

    Java中String类的方法及说明.pdf

    20. String replaceFirst(String regex, String replacement):使用给定的replacement替换此字符串中匹配给定正则表达式的第一个子串。21. String[] split(String regex):根据给定的正则表达式将字符串分割成一个...

    String类方法使用例子

    - `replaceAll(String regex, String replacement)`: 使用正则表达式替换匹配的子串。 示例: ```java String searchStr = "Java"; int index = searchStr.indexOf("a"); // 1 String replaced = searchStr....

    有关String的测试程序包含string内部一些函数

    11. **`replace(char oldChar, char newChar)` 和 `replace(CharSequence target, CharSequence replacement)`**:这些方法用于替换字符串中的特定字符或子串。 12. **`split(String regex)`**:此方法根据给定的...

    char,string全部函数方法说明

    `replace(char oldChar, char newChar)`和`replaceAll(String regex, String replacement)`用于替换字符串中的特定字符或符合正则表达式的部分。 此外,`concat(String str)`连接两个字符串,`compareTo(String ...

    信息办公凯撒java版SaaS OA协同办公软件 v2.0-saas-oa.zip

    replace( string1, string_to_replace, [ replacement_string ] ) string1 is the string to replace a sequence of characters with another set of characters. string_to_replace is the string that will be ...

    String方法使用方法例子续--android

    - `replaceAll(String regex, String replacement)`: 使用正则表达式进行替换。 5. **分割字符串** - `split(String regex)`: 根据正则表达式将字符串分割成数组。 6. **连接字符串** - `concat(String str)`: ...

    String详解

    4. **替换操作**:使用`replace(char oldChar, char newChar)`或`replaceAll(String regex, String replacement)`方法替换字符串中的某些字符或模式。 ```java String replaced = text.replace('p', 'x'); // ...

    String练习

    - `replace(char oldChar, char newChar)`和`replace(CharSequence target, CharSequence replacement)`用于替换指定字符或子字符串。 8. **分割字符串**: - `split(String regex)`根据正则表达式将字符串分割...

    C# aspose.word 批量替换文件夹下所有word文件里的字符串代码

    public static void BatchReplaceStringInWordFiles(string folderPath, string oldText, string newText) { if (!Directory.Exists(folderPath)) { Console.WriteLine($"指定的文件夹路径'{folderPath}'不存在。...

    NIST SP800-56A rec2 comments.pdf

    because although it is an alternate text for to 56A to say, (i) it is not said in 56A, and (ii) the red styling is probably sufficient to delimit the replacement of substitution text, but if not they...

    string类的常用方法.zip

    - `replaceAll(String regex, String replacement)`:使用正则表达式进行替换。 5. **分割与合并方法**: - `split(String regex)`:使用正则表达式分割字符串。 - `join(CharSequence... elements)`:将多个...

    Prototype String对象 学习

    【Prototype String对象学习】 在JavaScript中,Prototype是一个库,它扩展了JavaScript的内置对象,包括String对象。这里的“Prototype String对象”是指Prototype库为JavaScript原生的String对象添加的一些额外...

    PHP常用函数

    2.Ereg_replace 函数:string Ereg_replace(string pattern, string replacement, string string); 该函数可用于替换文本,当参数 pattern 与参数 string 中的字串匹配时,他就被参数 replacement 的内容所替换。 3....

Global site tag (gtag.js) - Google Analytics