How to pad a string with spaces in Ruby? - ruby

Is there a Ruby function that can pad a string?
Original [477, 4770]
Expected ["477 ", "4770 "]

You should use String#ljust from Ruby standard library:
arr = [477, 4770]
strings = arr.map { |number| number.to_s.ljust(5) }
# => ["477 ", "4770 "]

You need the method String#ljust. Here is an example:
t = 123
s = t.to_s.ljust(5, ' ')
Please note that ' ' is the default padding symbol. I only added it for clarity.

arr = [477, 4770]
arr.collect {|num| num.to_s.ljust(5)}

You can use printf formatting from Kernel as well :
arr = [477, 4770]
arr.map { |i| "%-5d" % i }

Related

How can I shorten the following Ruby code?

I have an array of hashes, all with the same keys, all with a key of id. I need a comma delimited string of ids.
arr_widgets = []
widgets.each do |widget|
arr_widgets.push(widget['id'])
end
str_widgets = arr_widgets.join(',')
Have you tried something like this?
str_widgets = widgets.map { |w| w['id'] }.join(',')
There is no need to create an intermediate array.
widgets = [
{"id"=>"dec"}, {"id"=>21}, {"id"=>2020}, {"id"=>"was"},
{"id"=>"the"}, {"id"=>"shortest"}, {"id"=>"day"}, {"id"=>"of"},
{"id"=>"the"}, {"id"=>"longest"}, {"id"=>"year"}
]
Note that two values are integers.
s = widgets.each_with_object(String.new) do |widget, s|
s << ',' unless s.empty?
s << widget["id"].to_s
end
puts s
#=> "dec,21,2020,was,the,shortest,day,of,the,longest,year"

Split with map! doesn't work

Why map! doens't work with a splited string ?
str = "abcd"
str.split('').map! { |x| x + "!" }
str # => "abcd"
I expected this would return ["a!","b!","c!","d!"]
str.split('') returns a new array. Calling .map! against the new string does not change the original str.
Assigning the result of str.split('') back to str:
str = str.split('')
str.map! { |x| x + "!" }
str # => ["a!", "b!", "c!", "d!"]
Or, assigning the whole result back to the str:
str = str.split('').map! { |x| x + "!" }
str # => ["a!", "b!", "c!", "d!"]
NOTE
Using same variable for saving string initially, then saving array could confuse the reader of the code. You'd better to use different variable for array;
arr = str.split('')
arr.map! { |x| x + "!" }
arr # => ["a!", "b!", "c!", "d!"]
Because you are updating in-place yes, but that array object that you waste because you don't save its instance anywhere.
characters = "abcd".split('')
characters.map! { |x| x + "!" }
characters
Note that you can move from split('') to chars
You also can use #chars:
> "abcd".chars.map { |x| x + '!' }
=> ["a!", "b!", "c!", "d!"]

how I could do a gsub with array elements?

How I could replaces a string like this
I think something like this
inputx.gsub(/variable1/,string1.split(";")[i])
But I dont know How I could do this code
name1;variable1
name;variable1
name3;variable1
by
dog;watch;rock
For obtain this
name1;dog
name;watch
name3;rock
string1 => dog;watch;rock ; this string Im trying to split for replace each string variable1
Please help me
subst = "dog;watch;rock".split ';'
input.gsub(/variable1/) do subst.shift end
#⇒ "name1;dog \n name;watch \n name3;rock"
Given (assuming) this input:
inputx = <<-EOD
name1;variable1
name;variable1
name3;variable1
EOD
#=> "name1;variable1\nname;variable1\nname3;variable1\n"
string1 = 'dog;watch;rock'
#=> "dog;watch;rock"
You can chain gsub and with_index to perform a replacement based on its index:
inputx.gsub('variable1').with_index { |_, i| string1.split(';')[i] }
#=> "name1;dog\nname;watch\nname3;rock\n"
You could also perform the split beforehand:
values = string1.split(';')
#=> ["dog", "watch", "rock"]
inputx.gsub('variable1').with_index { |_, i| values[i] }
#=> "name1;dog\nname;watch\nname3;rock\n"
I'm not sure there's a way to do it using .gsub(). One simple way to achieve what you want to is the following:
str = "dog;watch;rock"
array = str.split(";")
array.each_with_index do |str, i|
array[i] = "name#{i + 1};#{str}"
end
puts array
Output:
name1;dog
name2;watch
name3;rock
file intro2 => dog;watch;rock
file intro
name1;variable1
name;variable1
name3;variable1
ruby code
ruby -e ' n=0; input3= File.read("intro");string1= File.read("intro2") ;input3x=input3.gsub("variable1") { val =string1.split(";")[n].to_s; n+=1; val } ;print input3x' >gggf

Get the number of gsub substitutions in Ruby

gsub returns the string, or nil. Is there a way to have it return the number of replacements it has made?
I can think of using gsub block like this:
count = 0
str.gsub(/pat/) { |a| count+=1; "replacement" }
Example:
str = "lets replace all s with S"
count = 0
str.gsub("s") { |a| count+=1; "S" }
count
#=> 2
In Ruby gsub without second argument returns an Enumerator and you can use it:
str = 'your string'
new_str = str.gsub(/your/, 'my')
count = str.gsub(/your/).count

Ruby - How to add a character at the beginning and end of a string

How do I add a apostrophe at the beginning and end of a string?
string = "1,2,3,4"
I would like that string to be:
'1','2','3','4'
Not sure, if this is what you want:
>> s = "1,2,3,4"
>> s.split(',').map { |x| "'#{x}'" }.join(',')
=> "'1','2','3','4'"
result = []
"1,2,3,4".split(',').each do |c|
result << "'#{c.match /\d+/}'"
end
puts result.join(',')
'1','2','3','4'
We can use regular expression to find digits
string = "1,2,3,4"
string.gsub(/(\d)/, '\'\1\'')
#=> "'1','2','3','4'"
str.insert(0, 'x')
str.insert(str.length, 'x')
After seeing your edit.
q = "1,2,3,4"
ar = q.split(',')
ar.each{|i| i.insert(0, "'").insert(-1, "'")}
q = ar.join(',')

Resources