Hi Jens,

Jens Luedicke [19/01/02 16:32 +0100]:
> I want to delete an element from an array
> using the following code:
> 
> use Inline Ruby => <<CODE;
> 
> def remove_from_array(array,elem)
>       array.delete elem
>       return array
> end
> 
> CODE
> 
> The code doesn't work like I want, because
> I get the following error:
> 
> #<ArgumentError: wrong # of arguments(42 for 2)>

You have to make sure you call it like this:

$new_aref = remove_from_array($aref, $elem);

The reason you have to pass a *reference* is that Perl expands arrays in
parameter lists by default, meaning you sent every element of the array as a
separate argument. That's not cool with Ruby.

It returns a reference (not an array) because in Ruby, everything is a
reference. Inline::Ruby has some compile-time options about whether to
flatten arrays as they are returned. I haven't documented them because I
don't think you should do that.

That's the short answer. If you want the long one, read my PS, otherwise just
use this code:

----8<----
use Data::Dumper;
use Inline Ruby => <<CODE;

def remove_from_array(array, elem)
  array.delete elem
  return array
end

CODE

$aref = [qw(simon frank neil harry)];
$new_aref = remove_from_array($aref, "neil");
print Dumper $new_aref;
---->8----

Later,
Neil

PS: the compile-time options are defined in rb2pl.h:

o CHECK_CONTEXT
  If defined, enables the following two definitions.

o FLATTEN_ARRAYS
  If defined, then if a Ruby subroutine returns an array, and the subroutine
  was called in "array context", then the array is flattened onto Perl's
  return value stack.

  NOTE: if this is enabled, you can't tell the difference between the two
  return values for this function:

  def return_element(a)
    if a == "list"
      return [0]
    else
      return 0
    end
  end

  In the first case, the [0] is flattened onto Perl's stack, giving an array
  with one element: @a = (0).
  In the second case, the 0 is pushed onto Perl's stack, also giving an array
  with one element: @a = (0).

  By default, this IS NOT enabled.

o FLATTEN_CALLBACK_ARGS
  If defined, then when a Perl iterator is called from Ruby, the argument
  passed to it will be flattened onto the Perl call stack, if the type of the
  Ruby argument is an array.

  NOTE: if enabled, you can't tell the difference between being called from
  'yield [3]' and 'yield 3', for similar reasons to the above argument for
  return values.

  By default, this IS enabled.

Currently the only way to set these options is to edit rb2pl.h before
building Inline::Ruby. It's very simple, and they are well-documented in the
header file.

Reply via email to