1

Okay, I'm new to ruby and I need some good advice on this. Python code:

 return [x for x in list if x == something]

Sorry for not filling in the stuff, but I can't really since I this question relates to other parts of my code I heard .map could do this but i'm not sure how. Can anyone explain this to me so I can select a certain value if it turns up to be true? Heres another example but a simple one should make sense though

def test():
    lists = ['dave','austin','bob','jimmy','john','jimmy']
    return [x for x in lists if x == 'jimmy']

That code returns

['jimmy','jimmy']

Part of the reason why I left my first example blank is because I want to be able to do this for future code that applies to this example. So if anyone can show me how to do this the ruby way that would be great because I've been confusing my self trying to figure it out.

2 Answers 2

1

Perhaps Enumerable#select is what you're after?

lists = ['dave','austin','bob','jimmy','john','jimmy']
lists.select{|x| x == 'jimmy'} # => ["jimmy", "jimmy"]
Sign up to request clarification or add additional context in comments.

4 Comments

Yes, thank you that is exactly what I needed you cleared that up really nicely, I don't know why I couldn't find anything on the internet that said that, must have been using bad search terms or something, thanks again though.
No problem, I'm sort of learning Python at the moment so I can sympathize :-)
For good measure, look at all the methods in the Enumerable module, there's a lot of good stuff in there.
the ruby solution also aligns with how such a solution might look in SQL as well ruby: lists.select{|x| x=='jimmy'} SQL: SELECT name FROM lists WHERE name="jimmy";
0

Yes. Also, apart form the "select" function, you might want to use "map" as well. Select is like the "if" clause and "map" is like the first clause in a Python list comprehension.

a = [1, 3, 4, 5, 6, 7, 8] b = a.select{|i| (i % 2).zero?}.map{|i| (i * 3)} puts b # 12 18 24

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.