pycall.rb icon indicating copy to clipboard operation
pycall.rb copied to clipboard

Conversion of a Python list into a ruby array

Open wynksaiddestroy opened this issue 4 years ago • 2 comments

Hey there,

pardon my probably stupid question. Let's assume I have a simple list:

words = PyCall.builtins.list(['Foo', 'Bar', 'Foobar'])

Is there any way to convert this list into a ruby array? Or get the content of this list otherwise?

Thanks in advance

wynksaiddestroy avatar Apr 03 '20 08:04 wynksaiddestroy

You need to put . between list and ( like:

words = PyCall.builtins.list.(['Foo', 'Bar', 'Foobar'])

mrkn avatar Apr 22 '20 01:04 mrkn

Thank you very much for your answer. Unfortunately I have another question. Assume I want to return only words with 3 characters or less:

words = ['Foo', 'Bar', 'Foobar']
short_words = PyCall.builtins.filter.('lambda word: len(word) < 4', words)

If I call PyCall.builtins.list.(short_words) I will get the following error:

PyCall::PyError (<class 'TypeError'>: 'str' object is not callable)

Can you tell me what I am missing here? Thanks in advance.

wynksaiddestroy avatar Apr 22 '20 09:04 wynksaiddestroy

@wynksaiddestroy You can pass a Proc object to Python function like:

irb(main):001:0> words = ['Foo', 'Bar', 'Foobar']
=> ["Foo", "Bar", "Foobar"]
irb(main):002:0> short_words = PyCall.builtins.filter.(->{ _1.length < 4 }, words)
=> <filter object at 0x7f1b369214b0>
irb(main):003:0> PyCall.builtins.list.(short_words)
=> ['Foo', 'Bar']

mrkn avatar Aug 25 '23 02:08 mrkn