0

I have an array of filenames in ruby. I want to select the filename that contains a specific string in it

for example

array = ["/some/place/once.txt", "/some/place/two.txt","/some/place/three.txt"]

and i want to select only the filename that has the word "two" in it

so I want to get filename = array.select { |e| e.include? "two" }

but for some reason filename contains everything that is in array. How to make it work?

5
  • It should work, and I can't reproduce your problem. What else is there between setting filename and checking filename? Commented Jul 13, 2020 at 18:27
  • nothing, i have the array first line (i receive it as a parameter) and the filename selection second line Commented Jul 13, 2020 at 18:45
  • 4
    Lena, try copy pasting in the code from your question into a new IRB console. You will see that it produces the expected result. Therefore there must be something else going on in your code that you're not showing us. Commented Jul 13, 2020 at 18:51
  • Do you want the file name and not the entire dir path? If so: array.select { |e| e.include? "two" }.map { |p| p.split("/").last } Otherwise your code seems to be working Commented Jul 13, 2020 at 19:09
  • @maxpleaner it ended up being cursive " that was causing the issue. Commented Aug 4, 2020 at 14:02

1 Answer 1

1

Given this data:

array = ["/some/place/once.txt", "/some/place/two.txt","/some/place/three.txt"]

You can always find all matching entries with grep and just take the first:

array.grep(/two/).first
# => ["/some/place/two.txt"]

Or you can always scan using find:

array.find { |s| s.include?('two') }
# => "/some/place/two.txt"

Using select should produce an array result of all matches, but is otherwise identical. Your behaviour cannot be reproduced.

Sign up to request clarification or add additional context in comments.

Comments

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.