mrkn / pycall.rb

Calling Python functions from the Ruby language
MIT License
1.06k stars 75 forks source link

Conversion of a Python list into a ruby array #114

Closed wynksaiddestroy closed 1 year ago

wynksaiddestroy commented 4 years ago

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

mrkn commented 4 years ago

You need to put . between list and ( like:

words = PyCall.builtins.list.(['Foo', 'Bar', 'Foobar'])
wynksaiddestroy commented 4 years ago

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.

mrkn commented 1 year ago

@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']