Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing array as a command argument

I am trying to pass an array to a ruby script from a command line and facing some issue.

Here is the problem:

require 'pp'

def foo(arr1, var, arr2, var2)
  puts arr1.class
  pp arr1
  pp arr1[0]
  puts arr2.class
  pp arr2
  pp arr2[0]
end

foo [1, 2], 3, [5, 6], 8

Here is the output:

Array
[1, 2]
1
Array
[5, 6]
5

All is fine so far. Now I change my script to accept argument from the command line:

require 'pp'

def foo(arr1,var)
  puts arr1.class
  pp arr1
  pp arr1[0]
end
foo ARGV[0],3

Here is the output:

jruby test.rb [1, 2], 3, [5, 6], 8
String
"[1,"
91
String
"2],"
50

As you can see, the array gets passed as a string and arr[0] basically prints the ascii value.

So the question is how do I pass an array from the command line , hopefully in one line. Also I believe this question is related to all shell invocations than just ruby ?

I am using bash shell.

Update: Just updated the question to indicate that there can be multiple arrays at different positions

like image 837
codeObserver Avatar asked Aug 19 '26 01:08

codeObserver


1 Answers

Here's a list of ways to accomplish this. Stay away from the eval-based solutions. My favorite (though I don't know ruby, but this is my favorite:

irb(main):001:0> s = "[5,3,46,6,5]"
=> "[5,3,46,6,5]"
irb(main):002:0> a = s.scan( /\d+/ )
=> ["5", "3", "46", "6", "5"]
irb(main):003:0> a.map!{ |s| s.to_i }
=> [5, 3, 46, 6, 5]
like image 180
Christian Mann Avatar answered Aug 20 '26 16:08

Christian Mann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!