简体   繁体   中英

ruby gsub with condition

I'm trying to replace a value from a dropdown if multiple conditions are met. I'm trying to do this with the gsub method.

在此处输入图片说明

scenario 1: if current selected value is 9.3.9 then value 9.4.1 should not be available

scenario 2: if current selected value is 9.3.10 then value 9.4.1 and 9.4.4 should not be available

Sorry for not including the code snippet. Below is the method I use to get my RDS instances. I already use gsub to check if the current version used is 9.3 and prevent an upgrade to 9.4. I want to change that to the scenario above.

    def available_engine_versions(instance)
      if instance.engine == RdsGeneric::RDS_TYPE_MYSQL
        # This custom override for certain MySQL cases suppresses the option to upgrade to 5.6 from 5.5.
        # Amazon cannot do direct updates from MySQL 5.5 to MySQL 5.6 for DBs created before 4/23/2014.
        # instance.instance.created_at -> Uses Amazon's date of creation, not the one stored by ActiveRecord
        if instance.nil? || instance.engine_version.start_with?('5.6.') || instance.instance.nil? || instance.instance.created_at >= Time.parse('2014-04-23')
          RdsConfiguration::rds_configurations[RdsGeneric::RDS_TYPE_MYSQL][:engine_versions]
        else
          RdsConfiguration::rds_configurations[RdsGeneric::RDS_TYPE_MYSQL][:engine_versions].select{ |type| type.to_f <= 5.5 }
        end
      elsif instance.engine == RdsGeneric::RDS_TYPE_POSTGRES
        RdsConfiguration::rds_configurations[RdsGeneric::RDS_TYPE_POSTGRES][:engine_versions].select{ |type| type.gsub(/(\d+\.\d+).*?$/,"\\1") == instance.engine_version.gsub(/(\d+\.\d+).*?$/,"\\1") } # no upgrades from e.g. 9.3.x to 9.4.y
      else
        RdsConfiguration::rds_configurations[instance.engine][:engine_versions]
      end
    end

I believe this will work:

selected_value = instance.engine_version.gsub(/(\d+\.\d+\.\d+).*?$/,"\\1")
RdsConfiguration::rds_configurations[RdsGeneric::RDS_TYPE_POSTGRES][:engine_versions].reject do |type|
  dropdown_entry = type.gsub(/(\d+\.\d+\.\d+).*?$/,"\\1")

  (dropdown_entry == "9.4.1" && selected_value == "9.3.9") || (["9.4.1", "9.4.4"].include?(dropdown_entry) && selected_value == "9.3.10")
end

Notice that I changed select to reject .

Knowing what the data looks like would help a lot. You may not need the gsub at all now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM