how I could do a gsub with array elements? - ruby

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

Related

Trying to remove punctuation without using regex

I am trying to remove punctuation from an array of words without using regular expression. In below eg,
str = ["He,llo!"]
I want:
result # => ["Hello"]
I tried:
alpha_num="abcdefghijklmnopqrstuvwxyz0123456789"
result= str.map do |punc|
punc.chars {|ch|alpha_num.include?(ch)}
end
p result
But it returns ["He,llo!"] without any change. Can't figure out where the problem is.
include? block returns true/false, try use select function to filter illegal characters.
result = str.map {|txt| txt.chars.select {|c| alpha_num.include?(c.downcase)}}
.map {|chars| chars.join('')}
p result
str=["He,llo!"]
alpha_num="abcdefghijklmnopqrstuvwxyz0123456789"
Program
v=[]<<str.map do |x|
x.chars.map do |c|
alpha_num.chars.map.include?(c.downcase) ? c : nil
end
end.flatten.compact.join
p v
Output
["Hello"]
exclusions = ((32..126).map(&:chr) - [*'a'..'z', *'A'..'Z', *'0'..'9']).join
#=> " !\"\#$%&'()*+,-./:;<=>?#[\\]^_`{|}~"
arr = ['He,llo!', 'What Ho!']
arr.map { |word| word.delete(exclusions) }
#=> ["Hello", "WhatHo"]
If you could use a regular expression and truly only wanted to remove punctuation, you could write the following.
arr.map { |word| word.gsub(/[[:punct:]]/, '') }
#=> ["Hello", "WhatHo"]
See String#delete. Note that arr is not modified.

Deleting a portion from a string in ruby

I just want to delete a portion from a string.
My string: "&product=Software"
Need output: "Software"
Tried delete, split , slice but doesn't work. Can someone help me on this? I am very very new to Ruby.
It's slightly surprising, but Ruby lets you use [] and assignment to "overwrite" the substring you want to replace:
x = "&product=Software"
x['&product='] = ''
x # "Software"
str = "&product=Software"
str['&product='] = '' # method 1
str.sub!('&product=', '') # method 2
But if you wanna be smarter about it...
str = '&product=Software&price=19.99'
h = {}
str.split('&').each do |s|
next if s.length == 0
key, val = s.split '='
h[key] = val
end
puts h # {"product"=>"Software", "price"=>"19.99"}
Another two ways of achieving this:
Using split:
2.3.0 :014 > "&product=software".split('=')[1]
=> "software"
Using sub:
2.3.0 :015 > "&product=software".sub(/^.*?=/,'')
=> "software"

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

How to pad a string with spaces in 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 }

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