Ruby Concatenate Strings and Add Spaces

Ruby concatenate strings and add spaces

[name, quest, favorite_color, speed].reject(&:empty?).join(' ')

Ruby string concatenation add space

Of course, you are missing spaces.

You could have done it like this:

def repeat(word, repeats = 2)
Array.new(repeats, word).join(" ")
end

Adding a space between variables

The gets.chomp method itself does not catch any spaces. You will have to add them yourself.

Another Ruby way how to do that is through the join method.

puts "So your full name is, #{[forename, middlename, surname].join(' ')}."

With David's suggestion to form a complete answer, use compact before the joining, in order to avoid empty middlename and doubling of space.

puts "So your full name is, #{[forename, middlename, surname].compact.join(' ')}."

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.

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 join array of strings with space between last two elements

Use two join() calls:

[company.name, company.street, [company.zipcode, company.city].join(' ')].join(', ')

This method is preferred if you have non-blank delimiter on which to join and/or an array argument. In your specific case, the solution by engineersmnky using "#{...} #{...}" is shorter and more clear.

Repeat a string with spaces between copies

You can try this approach:

def repeat(input, n)
([input] * n).join ' '
end


Related Topics



Leave a reply



Submit