简体   繁体   中英

Elegant, simple Ruby way to gsub!/sub! values in an array/hash with values in another one when in input?

I am converting inputs that have, ideally always, the following line inside:

本資料由(上市公司) “Name of a company in Chinese characters“公司提供

Until now I have the following:

input = gets

input.gsub!(/(本資料由\(上市公司\))(.{1,10})(公司提供)/)  {"
The following information has been provided by: #{$2}\n"}

Company_making_the_Announcement = /(The following information has been provided by: )(.+)/.match(input)

if Company_making_the_Announcement[2].match "如興"
input.gsub! Company_making_the_Announcement[2], "Roo Hsing Co., Ltd (TSEC:4414)"

elsif Company_making_the_Announcement[2].match "新潤"
input.gsub! Company_making_the_Announcement[2], "Shin Ruenn development Co., LTD. (GTSM:6186)"

elsif Company_making_the_Announcement[2].match "遠東商銀"
input.gsub! Company_making_the_Announcement[2], "Far Eastern International Bank Ltd. (TSEC:2845)"

end

The above code works just fine but it is sort of clumsy, especially since the list of companies is in the thousands and the code will grow enormously as I add a new company. I was thus thinking of a more efficient, elegant way to do this. I thought that working with arrays/hashes might do the trick, but I am not having luck since the below code keeps returning errors, no matter how I modify it:

companieslist = [{chin: '如興', eng: 'Roo Hsing Co., Ltd (TSEC:4414)' }, {chin: '新潤', eng: 'Shin Ruenn development Co., LTD. (GTSM:6186)' }]

Company_making_the_Announcement = /(The following information has been provided by: )(companieslist[:chin])/.match(input) 

If Company_making_the_Announcement[2].match (companieslist[:chin])
Input.gsub! Company_making_the_Announcement[2], (companieslist[:eng])

end

So, in short, what would be an efficient way to match values in an array (Chinese names) to values in another one (English names) and replace the first value with the second when they appear in an input?

Thanks a lot

You're on the right track, just not taking advantage of the hash. Instead of an array of hashes, just use a hash, with chinese company name as key, english name as value.

companies = {'如興': 'Roo Hsing Co., Ltd (TSEC:4414)', '新潤': 'Shin Ruenn development Co., LTD. (GTSM:6186)' }

input = "如興 blah blah blah"

companies.each do |k,v|
  input.gsub!("#{k}", "#{v}")
end

puts(input)
# Roo Hsing Co., Ltd (TSEC:4414) blah blah blah

Note this assumes you want to translate every instance of every chinese company name in place. If the company names overlap, you'd need a slightly different approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM