1

I am trying to split a string, and output the different parts, whats the best practice for rails 3 ?

String: "book_page_title" Seperator: "_"

I want to have book, page and title as seperate variables, so that I can perform actions on them..

Any help is appreciated. Also, I am having trouble finding good reference sites, with examples like PHP have, and suggestions ?

5 Answers 5

4

To split:

book,page,title = string.split('_')

And to recombine:

string = [book,page,title].join('_')
Sign up to request clarification or add additional context in comments.

Comments

1

use

split('_') 

method it gives array.

Comments

1

Try ruby+string+doc in google, you will get http://ruby-doc.org/core/classes/String.html as the first result, and you can see a number of string functions in this link. You can see split there.

splitted_array = "book_page_title".split("_")
=> ["book", "page", "title"]

splitted_array.each do |string|
  #..do manipulations here
end

1 Comment

rubyprince I like this. first answer to also address outputting the various parts.
0

"book_page_title".split("_") will return you array of strings. So you can access every element via [].

splitted = "book_page_title".split("_") # ["book", "page", "title"]
puts splitted[0] # gives "book"
puts splitted[1] # gives "page"
puts splitted[2] # gives "title"

2 Comments

Great! Thanks for helping, I think "var.split("_")[1]" looks clean.. love how rails can output so compact code : )
@jakobk: the credit for this compact code goes to Ruby and I too love it :)
0
a = "book_page_title".split("_")

a.each do |i|
  instance_variable_set("@#{i}", "value")
end

@book #=> *value*
@page #=> *value*
@title #=> *value*

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.