Skip to content

Instantly share code, notes, and snippets.

@sts
Created April 17, 2015 15:45
Show Gist options
  • Save sts/da08d3710704c6a64cab to your computer and use it in GitHub Desktop.
Save sts/da08d3710704c6a64cab to your computer and use it in GitHub Desktop.
a = ['1', '2']
a.collect { if 0 == 1 ; 'foo' ; end }.inspect #=> "[nil, nil]"
a.collect { if 0 == 0 ; 'foo' ; end }.inspect #=> "[\"foo\", \"foo\"]"
@IceDragon200
Copy link

I think you meant:

a = ['1', '2']

# since you have an Array of Strings, you'll need to compare against strings 
a.collect { |o| if o == '1' ; 'foo' ; end }.inspect #=> "[nil, nil]"
a.collect { |o| if o == '0' ; 'foo' ; end }.inspect #=> "[\"foo\", \"foo\"]"

EDIT1:
In case you wanted to get elements that match the condition:

# select expects that your block result will be a Boolean
a.select { |o| o == '1' } #=> [1]
a.select { |o| o == '0' } #=> []

EDIT2:
In the case you want to select and map:

a.each_with_object([]) { |o, ary| ary << 'foo' if o == '1' } #=> ['foo']
a.each_with_object([]) { |o, ary| ary << 'foo' if o == '0' } #=> []

@sts
Copy link
Author

sts commented Apr 17, 2015

partitions = [
 Hash[ :code => '0700', :sector_start => 63, :size_unit => 'GiB', :size => 500 ],
 Hash[ :code => '8300', :sector_start => 63, :size_unit => 'GiB', :size => 500 ]
]

windows_partitions = partitions.select { |partition|
  partition[:code] == '0700' and
  partition[:sector_start] == 63 and
  partition[:size_unit] == 'GiB' and
  partition[:size].to_i > 400
}

windows_partitions.inspect
#=> [{:code=>"0700", :sector_start=>63, :size_unit=>"GiB", :size=>500}]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment