anakin
anakin

Reputation: 365

Convert Python code into Ruby

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.

Upvotes: 1

Views: 2020

Answers (2)

jleeothon
jleeothon

Reputation: 3166

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

Upvotes: 0

Abe Voelker
Abe Voelker

Reputation: 31632

Perhaps Enumerable#select is what you're after?

lists = ['dave','austin','bob','jimmy','john','jimmy']
lists.select{|x| x == 'jimmy'} # => ["jimmy", "jimmy"]

Upvotes: 1

Related Questions