String Concatenation in Ruby

String concatenation in Ruby

You can do that in several ways:

  1. As you shown with << but that is not the usual way
  2. With string interpolation

    source = "#{ROOT_DIR}/#{project}/App.config"
  3. with +

    source = "#{ROOT_DIR}/" + project + "/App.config"

The second method seems to be more efficient in term of memory/speed from what I've seen (not measured though). All three methods will throw an uninitialized constant error when ROOT_DIR is nil.

When dealing with pathnames, you may want to use File.join to avoid messing up with pathname separator.

In the end, it is a matter of taste.

Ruby on Rails String Concatenation

Instead of

 @post.data_string << "as"

you could use

 @post.data_string =  @post.data_string + "as"

Ruby differences between += and to concatenate a string

The shovel operator << performs much better than += when dealing with long strings because the shovel operator is allowed to modify the original string, whereas += has to copy all the text from the first string into a new string every time it runs.

There is no += operator defined on the String class, because += is a combined operator. In short x += "asdf" is exactly equivalent to x = x + "asdf", so you should reference the + operator on the string class, not look for a += operator.

Simple string concatenation in rails in view page

in view

<%
var1 = "ruby"
var2 = "on"
var3 = var1 + var2
%>

Finally

<% f_var = "Ruby #{var3}"%>

but this type of code is not recommended in view as it does not look good. You should use helper method for this type of requirement

String concatenation in Rails 3

The parser is interpreting +'/' as the first parameter to the to_s method call. It is treating these two statements as equivalent:

> params['controller'].to_s +'/'
# NoMethodError: undefined method `+@' for "/":String

> params['controller'].to_s(+'/')
# NoMethodError: undefined method `+@' for "/":String

If you explicitly include the parenthesis at the end of the to_s method call the problem goes away:

> params['controller'].to_s() +'/'
=> "posts/"

Why do two strings separated by space concatenate in Ruby?

Implementation details can be found in parse.y file in Ruby source code. Specifically, here.

A Ruby string is either a tCHAR (e.g. ?q), a string1 (e.g. "q", 'q', or %q{q}), or a recursive definition of the concatenation of string1 and string itself, which results in string expressions like "foo" "bar", 'foo' "bar" or ?f "oo" 'bar' being concatenated.

Ruby On Rails: Concatenate String in loop

Try this

assets = Asset.where({ :current_status => ["active"] }).all
string = ""
if assets.present?
assets.each do |a|
string = string + ":"+ a.movie_title
end
end


Related Topics



Leave a reply



Submit