I want to change the program so that I don't use to_proc with the select method.

Asked 2 years ago, Updated 2 years ago, 46 views

For samples that do not write blocks often, specify & symbols for the arguments of the select method and
 (1..10).select(&:even?)
Samples written like this are common, but
How do you write conditions that refer to attributes of a class?

Square=Struct.new(:row,:column)

squares = [ ]

squares<<Square.new(10,20)
squares<<Square.new(50,20)
squares<<Square.new(20,20)

# I don't want to write blocks like select(...) here.
psquares.select {|s|: ==.to_proc[20, s.row]}# Extract 20 rows
# psquares.select {|s|20==s.row}You're telling me to write it like this...

ruby

2022-09-30 20:22

2 Answers

You can do it using a gem called lambda_driver.

square.select(&:row>>20._(:==))

I think it's best to be honest with square.select{|s|20==s.row} as you write.


2022-09-30 20:22

If you really want to use select(...), you can write like this.

Square=Struct.new(:row,:column)

squares = [ ]

squares<<Square.new(10,20)
squares<<Square.new(50,20)
squares<<Square.new(20,20)

f=->(s){s.row==20}

squares.select(&f)

Or something like this.

def test(s,v))
  s.row==v
end

Square=Structure.new(:row,:column)

squares = [ ]

squares<<Square.new(10,20)
squares<<Square.new(50,20)
squares<<Square.new(20,20)

squares.product([20]).select(&method(:test)) .map(&:first)

I think it's different from the answer I'm looking for...

But if you don't have any particular reason,

square.select {|s|s.row==20}

It would be most honest and easy to understand.

Add

What does test(s,v)) mean?

If you define a method and execute code without parentheses, such as def test(s,v), you get the following error:

ArgumentError: wrong number of arguments (1 for 2)
    from(irb): 1: in `test'
    from(irb):13:in `select'
    from (irb): 13
    from/Users/jit/.rbenv/versions/2.2.3/bin/irb:11:in`<main>'

This means that the test method is defined to receive two arguments, but when called by the select method, only one argument was passed (=one array was passed), resulting in an error.

def test(s,v)) means that you have defined one argument.
However, when an array is passed, the first and second elements are substituted for s and v, respectively.(It's complicated)

If you find it difficult to understand, consider the following code written in one line:

def test(args)
  s=args[0]
  v=args[1]
  # s,v = args is acceptable
  s.row==v
end

Square=Structure.new(:row,:column)

squares = [ ]

squares<<Square.new(10,20)
squares<<Square.new(50,20)
squares<<Square.new(20,20)

squares.product([20]).select(&method(:test)) .map(&:first)


2022-09-30 20:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.