1

I'm trying to enhance my script below to print only the unique values that shud be of *) 6 characters - alphanumeric and in lowercase or *) words starting with map ,from the list of files in a directory

What I've tried

values = []
@files = Dir.glob("*.txt")
for values in @files
 file = File.read(values)
 file.split(' ').each do |line|
    values.push(line.gsub(',', '')) if line.match(/[a-z0-9]{6}/) end or unless values.include? line.gsub(',', '') or line.match(/map_.*/)
  end
end

puts values

Example,

file 1

[id]
col1 = map_dr_check, map_iop, foo123
col2 = bar123, FOO123
col3 = ta2ngo, bar123

[/id_check]
@col2 = dr
@col1 = r

file 2

[id]
col1 = map_dr_check, map_iop, foo123
col2 = alp23r
col3 = poi90k, bar123

[/id_check]
@col2 = *
@col1 = r

Expected output

map_dr_check
map_iop
foo123
ta2ngo
bar123
alp23r
poi90k

but my output is empty and I'm not sure where I've gone wrong with my regex or whether the .match method is supported with string.

4
  • Oh my what have you done if line.match(/[a-z0-9]{6}/) end or unless values.include? line.gsub(',', '') or line.match(/map_.*/) Commented Feb 19, 2018 at 15:21
  • @engineersmnky : I'm sorry about the ill formed syntax, Im very new to Ruby and just exploring concepts. Can you please correct me here, thank you. Commented Feb 19, 2018 at 15:30
  • new to ruby or new to programming? My reason for asking is if you are coming from another language your conditional is equivalent to if line.match(/[a-z0-9]{6}/) or (if not(values.include?(line.gsub(',', '') or line.match(/map_.*/)))) which I am sure you would not write anywhere else either. Additionally in ruby one would usually use || in place of or as it has a different (higher) precedence. Commented Feb 19, 2018 at 15:52
  • @engineersmnky :My apologies, new to programming. any help is really appreciated, thanks again. Commented Feb 19, 2018 at 15:55

1 Answer 1

1

Use Enumerable#grep:

input = ... # get it from files, or whatever
input.split.grep(/\A[[:alnum:]]{6}\z|\Amap_.*/)

For your example (untested):

Dir.glob("*.txt").flat_map do |file|
  File.read(file).split.grep(/\A[[:alnum:]]{6}\z|\Amap_.*/)
end
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for looking in to this, when I tried your above solution Dir.glob("*.txt").flat_map do |file| value= file.read(file).split.grep(/\A[[:alnum:]]{6}\z|\Amap_.*/) puts value end I'm facing the below error undefined method `flat_map' for #<Array:0x7fc1aa2941b8> (NoMethodError)
Upgrade your ruby, flat_map is there for ages: ruby-doc.org/core/Enumerable.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.