简体   繁体   中英

How to split string variables in Ruby

I have this mini-function:

def dummy_string_management(val)
    parts = val.split(' ')
    return "#{parts[0]}" + " -done!"
end

I'm calling the function like this:

myString = "This is a string"
<%= dummy_string_management(myString) %>

But I'm getting this error:

undefined method `split' for This is a string

How can I split the variable sent as the function parameter?

Using IRB to test your code:

>> def dummy_string_management(val)
|        parts = val.split(' ')
|        return "#{parts[0]}" + " -done!"
|    end
:dummy_string_management
>> dummy_string_management('foo bar')
"foo -done!"

So, the code is behaving correctly. (It's not well written Ruby but that's a different problem.)

You can't use

myString = "This is a string"
<%= dummy_string_management(myString) %>

in a view/ERB template. The line myString = "This is a string" won't be interpreted as you expect, nor should you get the error message you said. At a minimum you need to define the variable inside <% ... %> but really that should occur in a controller and the result of dummy_string_management(myString) should be assigned to a variable which is directly accessed in the view.

Just as an idea of how we'd probably write your method:

def dummy_string_management(val)
    val.split.first + ' -done!'
end

How that works is left for you to figure out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM